JavaScript Notes
Understand the real difference between null and undefined in JavaScript. Learn when to use each, how they behave in comparisons, typeof results, and common pitfalls.
null and undefined are two of the most confusing concepts for JavaScript beginners. They both mean "no value" in some sense — yet they are completely different in origin, intent, and behavior. Master this distinction and you'll avoid a whole category of bugs.
Real World Analogy
Imagine a form on a website asking for your middle name:
- If the form hasn't been filled out yet, the field is
undefined— the system doesn't have any information yet. - If you deliberately check a box saying "I don't have a middle name", that's
null— you actively communicated that there's intentionally nothing there.
Same concept: both mean "no name", but for different reasons and from different sources.
Where Does Each Come From?
Code Examples: undefined in Action
1. Declared but not assigned
let score;
console.log(score); // undefined
console.log(typeof score); // "undefined"undefined undefined
2. Missing function argument
function greet(name) {
console.log("Hello,", name);
console.log(typeof name);
}
greet("Ananya"); // name = "Ananya"
greet(); // name = undefined (not provided)Hello, Ananya string Hello, undefined undefined
3. Function with no return value
function doNothing() {
// no return statement
}
const result = doNothing();
console.log(result);
console.log(typeof result);undefined undefined
4. Non-existent property
const user = { name: "Karan", age: 22 };
console.log(user.email); // property doesn't existundefined
Code Examples: null in Action
1. Explicitly set to null
let currentUser = null; // No user is logged in
console.log(currentUser);
console.log(typeof currentUser); // ⚠️ "object" — famous JS bug!null object
2. Resetting state
let sessionToken = "abc123xyz";
console.log("Session active:", sessionToken);
// User logs out — intentionally clear the session
sessionToken = null;
console.log("Session after logout:", sessionToken);Session active: abc123xyz Session after logout: null
3. Function returning null to signal "not found"
{ id: 1, name: 'Simran' }
nullThe Equality Trap: == vs ===
This is the most important difference to memorize:
console.log(null == undefined); // true (loose equality — they're "nullish")
console.log(null === undefined); // false (strict equality — different types!)
console.log(null == 0); // false
console.log(null == false); // false
console.log(undefined == 0); // false
console.log(undefined == ""); // falsetrue false false false false false
💡null == undefinedistruebecause ECMAScript specifically defines these two as loosely equal to each other (and only to each other). This is actually useful — you can check for "either null or undefined" with a single== nullcheck.
Memory Model: How They're Stored
Comparison Table
| Feature | null | undefined |
|---|---|---|
| Type | object *(JS bug)* | undefined |
| Set by | Developer (explicit) | JavaScript engine (automatic) |
| Meaning | Intentionally empty | Not yet assigned |
typeof | "object" | "undefined" |
Loose equality == | null == undefined → true | same as null |
Strict equality === | null === undefined → false | same |
| Falsy? | ✅ Yes | ✅ Yes |
| JSON.stringify | "null" (included) | omitted from JSON |
| Default param trigger | ❌ Does NOT trigger | ✅ Triggers default |
The Default Parameter Behavior
This is a subtle but critical difference:
function createUser(name = "Guest") {
console.log("User:", name);
}
createUser(); // no argument → undefined → triggers default
createUser(undefined); // explicit undefined → triggers default
createUser(null); // explicit null → does NOT trigger default!User: Guest User: Guest User: null
⚠️ Default parameters only activate when the argument isundefined, NOT when it'snull. This trips up many developers!
JSON Behavior
const data = {
name: "Rohan",
age: null,
email: undefined
};
console.log(JSON.stringify(data));{"name":"Rohan","age":null}undefinedproperties are silently omitted from JSON (because JSON has noundefined).nullis preserved asnull. This is critical when sending data to a server.
Nullish Coalescing ?? and Optional Chaining ?. (Modern JavaScript)
Anonymous 0 No score
// ?. optional chaining — safely access properties that might be null/undefined
const user = null;
console.log(user?.name); // undefined (no crash!)
console.log(user?.address?.city); // undefined (chains safely)undefined undefined
Common Mistakes
❌ Mistake 1: Not checking for null before accessing properties
// ❌ WRONG — crashes if findUser returns null
const user = findUser(999);
console.log(user.name); // TypeError: Cannot read properties of null// ✅ CORRECT — check before accessing
const user = findUser(999);
if (user !== null) {
console.log(user.name);
} else {
console.log("User not found");
}
// ✅ Even better with optional chaining
console.log(user?.name ?? "User not found");❌ Mistake 2: Using typeof to check for null
// ❌ WRONG — typeof null is "object", so this check fails
function processData(data) {
if (typeof data === "object") {
console.log(data.value); // crashes if data is null!
}
}// ✅ CORRECT
function processData(data) {
if (data !== null && typeof data === "object") {
console.log(data.value);
}
}❌ Mistake 3: Using == null when you mean === null
// This might be surprising...
console.log(null == undefined); // true
console.log(null == false); // false
console.log(null == 0); // false
// ✅ Use == null INTENTIONALLY to check for "null OR undefined"
function processIfProvided(value) {
if (value == null) { // catches both null and undefined
console.log("No value provided");
return;
}
console.log("Value:", value);
}
processIfProvided(null); // "No value provided"
processIfProvided(undefined); // "No value provided"
processIfProvided(0); // "Value: 0"No value provided No value provided Value: 0
Key Takeaways
undefined= JavaScript assigned this automatically (declared but not initialized, missing argument, no return value)null= You as a developer assigned this intentionally ("empty on purpose")typeof null === "object"is a JavaScript bug — null is NOT an objectnull == undefinedistrue(loose), butnull === undefinedisfalse(strict)- Both are falsy values
- Default parameters trigger on
undefinedbut NOT onnull undefinedis dropped from JSON.stringify;nullis preserved- Use
??(nullish coalescing) and?.(optional chaining) to handle both safely in modern JS - Best practice: use
nullto intentionally empty a value; let JavaScript handleundefined
Interview Questions & Answers
Q1. What is the difference between null and undefined in JavaScript?
Answer: Both represent "no value" but differ in origin and intent:
undefinedis automatically assigned by JavaScript to a declared-but-uninitialized variable, a function parameter that wasn't passed, or a function with no return statement.nullis intentionally assigned by the developer to signify that a variable has been explicitly set to have no value.
Q2. Why does typeof null return "object"?
Answer: This is a historical bug in JavaScript dating back to its original 1995 implementation. The internal type tags used a value of 0 for objects, and null was represented as a null pointer (all zeros), which accidentally matched the object type tag. The bug was discovered but never fixed to avoid breaking the web.
Q3. What does null == undefined evaluate to and why?
Answer: It evaluates to true. The ECMAScript specification explicitly defines that null and undefined are loosely equal only to each other (and to nothing else). This is useful: you can write if (value == null) to check for *either* null *or* undefined in one condition.
Q4. Do default function parameters apply when you pass null?
Answer: No. Default parameters only kick in when the argument is undefined (either not passed or explicitly passed as undefined). If you pass null, the default is not applied — null is used as the value. Example:
function greet(name = "Guest") { return name; }
greet(null) // returns null
greet(undefined) // returns "Guest"Q5. How do you safely access a property that might be on a null or undefined object?
Answer: Use optional chaining (?.): user?.address?.city returns undefined instead of throwing a TypeError if user or address is null/undefined. Combine with nullish coalescing (??) to provide a fallback: user?.address?.city ?? "Unknown".
Q6. What happens to undefined values in JSON.stringify?
Answer: undefined values are omitted from the JSON output. JSON has no representation for undefined. null values ARE included in JSON. This means if you send an object with undefined properties to a server, those properties will disappear in transit.
Q7. What is the nullish coalescing operator ?? and how does it differ from ||?
Answer: ?? returns the right-hand side only when the left side is null or undefined. || returns the right-hand side for any falsy value (including 0, "", false). This matters when 0 or empty string are valid values you want to keep: score ?? "N/A" keeps 0 as a score, while score || "N/A" would replace 0 with "N/A".
Q8. Which is better to use as a developer — null or undefined?
Answer: Best practice: let JavaScript produce undefined naturally (don't assign undefined manually) and use null intentionally when you want to explicitly clear a value. For example, when a user logs out, set currentUser = null rather than currentUser = undefined. This makes intent clear in your code.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript null vs undefined – Complete Guide with Differences, Examples & Interview Q&A.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, basics, null, undefined
Related JavaScript Master Course Topics