🤯 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.
✅ What is Number.isNaN()
?
Number.isNaN()
is a method in JavaScript used to check if a value is exactly the special value NaN
(Not-a-Number) — and nothing else.
jsCopyEditNumber.isNaN(value)
It returns:
true
→ only if the value isNaN
false
→ for all other values (even if they’re not numbers)
⚠️ Why is Number.isNaN()
Important?
Before Number.isNaN()
, developers used the global isNaN()
function, which converts the input to a number first, which could lead to confusing results.
jsCopyEditisNaN("hello") // true ❌ (coerced to NaN)
Number.isNaN("hello") // false ✅ (no coercion)
So, Number.isNaN()
is stricter and safer, because:
It doesn't do type coercion.
It only returns
true
if the value is really the specialNaN
value.
🤔 But why is NaN
tricky?
Because NaN
is the **only value in JavaScript that is not equal to itself.
jsCopyEditconsole.log(NaN === NaN); // false
So you cannot use ===
to check for NaN. That’s where Number.isNaN()
shines.
✅ Examples
jsCopyEditNumber.isNaN(NaN); // true
Number.isNaN(42); // false
Number.isNaN("NaN"); // false
Number.isNaN(undefined); // false
Number.isNaN("hello"); // false
Number.isNaN(0 / 0); // true
Number.isNaN(parseInt("abc")); // true
🧪 Practical Use Cases of NaN
in JavaScript
1. ✅ Validating User Input
When building forms or calculators, you might want to validate if a user entered a proper number.
function isValidNumber(input) {
const number = Number(input);
return !Number.isNaN(number);
}
console.log(isValidNumber("42")); // true
console.log(isValidNumber("abc")); // false
Using Number.isNaN()
ensures that you catch invalid number conversions without false positives.
2. 📦 Parsing API Data
APIs often return strings for numbers. Before doing calculations, ensure the values are actually numeric.
const data = { price: "abc" };
const price = parseFloat(data.price);
if (Number.isNaN(price)) {
console.error("Invalid price from API!");
}
This prevents runtime errors from bad data.
3. 🔢 Default Fallback Values
When a value might be NaN
, you can replace it with a default using isNaN()
or a ternary operator.
let userScore = Number("not_a_score");
userScore = Number.isNaN(userScore) ? 0 : userScore;
4. 📊 Detecting Corrupted Calculations
In complex mathematical operations, NaN
can silently appear. Catching it early helps you debug better.
function calculateRiskIndex(input) {
const risk = Math.log(input); // log of 0 or negative gives NaN
if (Number.isNaN(risk)) {
throw new Error("Invalid input for risk calculation");
}
return risk;
}
5. 🧹 Filtering Invalid Data from Arrays
You can use Number.isNaN()
to remove invalid numbers from datasets.
const rawData = [23, "42", "abc", NaN, 55];
const cleaned = rawData
.map(Number)
.filter(n => !Number.isNaN(n));
console.log(cleaned); // [23, 42, 55]
⚠️ Always use
Number.isNaN()
overisNaN()
to avoid unwanted type coercion.
🔍 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
