🤯 undefined, null, and NaN in JavaScript – Explained Clearly

If you're new to JavaScript (or even experienced), undefined
, null
, and NaN
can feel like three very confusing cousins.
They all seem to mean "nothing" — but they're very different kinds of nothing.
Let’s clear it all up, once and for all.
1️⃣ undefined
– The default “nothing”
🔍 What is it?
undefined
means: “This variable exists, but it hasn’t been assigned a value yet.”
✅ You get undefined
when:
let a;
console.log(a); // undefined (no value assigned)
function greet(name) {
console.log(name);
}
greet(); // undefined (no argument passed)
const obj = {};
console.log(obj.age); // undefined (property doesn’t exist)
❗ Important Notes:
undefined
is the default return value of functions that don’t return anything.Don’t manually assign
undefined
yourself. Usenull
instead when you intentionally mean “nothing”.
2️⃣ null
– Intentional emptiness
🔍 What is it?
null
is explicit nothing. It’s used to show “we have nothing here on purpose.”
✅ Example:
let userProfile = null; // User hasn’t logged in yet
const response = {
error: null,
data: []
};
❗ Important Notes:
typeof null
return object while typeof undefined return undefinedUse
null
to reset a variable, empty a field, or indicate an intentional absence.
3️⃣ NaN
– Not a Number (but still a number)
🔍 What is it?
NaN
is a special value that means: “This is not a valid number, even though we expected one.”
✅ Example:
console.log(0 / 0); // NaN
console.log(parseInt('abc')); // NaN
console.log(Math.sqrt(-1)); // NaN
❗ Important Notes:
typeof NaN === "number"
← Weird but true.
🔍 Side-by-Side Comparison
Feature | undefined | null | NaN |
Means | Variable exists, but no value | Intentionally empty | Invalid number |
Type | undefined | object (quirk) | number |
Use-case | Unassigned variables, missing params | Manual reset or empty slot | Bad math or invalid number conversion |
✅ When to Use What?
Situation | Use |
You haven’t assigned a value yet | Let it be undefined (automatic) |
You want to intentionally empty a variable or object | Use null |
You’re doing math and the result is invalid | JavaScript will give you NaN |
🧪 Quiz Yourself!
What will this log?
let a;
let b = null;
let c = "hello" * 3;
console.log(a); // ?
console.log(b); // ?
console.log(c); // ?
undefined
null
NaN
🎯 Final Tip
Use
null
intentionallyDon’t assign
undefined
manuallyAlways check for
NaN
usingNumber.isNaN()
Subscribe to my newsletter
Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
