Undefined, Null and NaN
JavaScript has three special values that all mean some kind of "nothing", and mixing them up causes real bugs. undefined means a value was never given. null means a value was deliberately set to empty. NaN means a calculation that should have produced a number failed. Each has its own type, its own sources and its own correct test. This lesson puts them side by side and shows how to keep them from leaking into your data.
In One Minute
undefined: never assigned. Comes from unassigned variables, missing properties and arguments, and functions withoutreturn.null: intentionally empty. Only appears when code (yours, an API's, the DOM's) sets it.NaN: "Not a Number", the result of failed numeric work, such asNumber("abc"). Its type is"number".- Test with
x === undefined,x === null,x == null(either one) andNumber.isNaN(x). - Use
??and?.to handlenullandundefined; validate numbers to keepNaNout.
Side by Side
undefined | null | NaN | |
|---|---|---|---|
| Meaning | No value given | Deliberately empty | Failed number |
typeof | "undefined" | "object" | "number" |
| Set by | JavaScript, automatically | Code, on purpose | Failed arithmetic or conversion |
Equal to itself (===) | Yes | Yes | No |
Number(x) | NaN | 0 | NaN |
| In JSON | Property is omitted | null | Becomes null |
| Correct test | x === undefined | x === null | Number.isNaN(x) |
| Falsy | Yes | Yes | Yes |
undefined: Never Assigned
let discount;
const student = { name: "Navika" };
function save() {}
function greet(name) { return name; }
console.log(discount);
console.log(student.grade);
console.log(save());
console.log(greet());
console.log([1, 2][5]);undefined
undefined
undefined
undefined
undefinedEvery one of these is JavaScript saying "nothing was put here": a declared but unassigned variable, a property that doesn't exist, a function with no return, a missing argument, an index past the end of an array.
null: Deliberately Empty
null never appears on its own; something has to set it. It says "we know about this, and there is nothing here":
const student = { name: "Advitha", scholarship: null, guardianPhone: null };
console.log(student.scholarship);
console.log("pattern".match(/x/));
console.log(JSON.parse('{"middleName": null}').middleName);
console.log(Object.getPrototypeOf(Object.prototype));null
null
null
nullThe student has no scholarship (known, and empty). A regular expression with no match returns null. JSON can represent null but not undefined. In the browser, document.querySelector returns null when no element matches. The prototype chain ends in null.
Testing for null and undefined
const values = [undefined, null, 0, "", false, NaN];
for (const v of values) {
console.log(String(v).padEnd(9), v === undefined, v === null, v == null);
}undefined true false true
null false true true
0 false false false
false false false
false false false false
NaN false false falseExplanation: v == null is true for exactly two values, null and undefined, and false for every other falsy value. It is the one place where many style guides allow ==, because it is a precise, well-known shortcut for "is it missing?". v === undefined || v === null says the same thing explicitly.
Handling Missing Values
The modern operators from the logical operators lesson are designed for null and undefined:
const record = { name: "Srihitha", contact: null, balance: 0 };
console.log(record.contact?.city ?? "No city on file");
console.log(record.balance ?? 100);
console.log(record.balance || 100);
record.notes ??= [];
record.notes.push("Paid by check");
console.log(record.notes);No city on file
0
100
['Paid by check']?. stops at null or undefined instead of throwing. ?? falls back only for null or undefined, keeping the real balance of 0, whereas || would wrongly replace it.
NaN: A Failed Number
NaN is a number value that represents "this should have been a number, but the calculation failed":
const total = [120, Number("85 dollars"), 45].reduce((a, b) => a + b, 0);
console.log(total);
console.log(NaN === NaN);
console.log(Number.isNaN(total));
console.log([NaN].includes(NaN), [NaN].indexOf(NaN));
console.log(Math.max(3, NaN, 7));NaN
false
true
true -1
NaNExplanation: one bad conversion turned the whole total into NaN, because any arithmetic with NaN gives NaN. It isn't equal to itself, so === NaN is useless; use Number.isNaN. includes finds it (SameValueZero) but indexOf doesn't (strict equality). Even Math.max returns NaN if any argument is NaN.
How They Behave in JSON
When data is saved or sent as JSON, the three values behave differently, and that can change your data:
const data = { a: undefined, b: null, c: NaN, list: [undefined, null, NaN] };
console.log(JSON.stringify(data));{"b":null,"c":null,"list":[null,null,null]}A property holding undefined disappears entirely, while undefined in an array becomes null. NaN becomes null everywhere. After a round trip through JSON, you can't tell the three apart, which is one more reason to keep NaN out of your data.
In Practice
The Fee Tracker cleans an imported record: missing fields become null (known to be empty), invalid amounts are rejected rather than stored as NaN, and the summary handles every case:
function clean(raw) {
const amount = raw.amount === undefined || raw.amount === "" ? null : Number(raw.amount);
if (Number.isNaN(amount)) throw new TypeError(`Bad amount for ${raw.name}: ${raw.amount}`);
return { name: raw.name, amount, note: raw.note ?? null };
}
function summary(r) {
return `${r.name}: ${r.amount == null ? "no amount yet" : "$" + r.amount}${r.note ? ` (${r.note})` : ""}`;
}
for (const raw of [{ name: "Navika", amount: "120", note: "check" }, { name: "Advitha" }, { name: "Zoe", amount: "12x" }]) {
try {
console.log(summary(clean(raw)));
} catch (err) {
console.log(err.message);
}
}Navika: $120 (check)
Advitha: no amount yet
Bad amount for Zoe: 12xCommon Mistakes
if (!value) to test for missing. Also true for 0, "" and false. Use value == null.
value === NaN. Always false. Use Number.isNaN(value).
typeof value === "null". Never true. Use value === null.
Assigning undefined to mean "empty". Use null, so undefined keeps meaning "never set".
Interview Corner
What is the difference between null and undefined?
undefined is the default value of anything not assigned (variables, missing properties and arguments, functions without return). null is an explicit "no value" assigned by a program. typeof undefined is "undefined", typeof null is "object" (a legacy bug). null == undefined is true; null === undefined is false. Number(null) is 0 but Number(undefined) is NaN, and JSON drops undefined properties but keeps null.
How do you check whether a value is NaN?
Number.isNaN(x), which doesn't coerce. x !== x is true only for NaN and also works. The global isNaN coerces first, so isNaN("abc") is true for a string.
What does this print?
Show solution
console.log(null + 1, undefined + 1, typeof NaN, null == 0, undefined == null);1 NaN number false truenull becomes 0 in arithmetic, undefined becomes NaN. NaN is a number. null loosely equals only undefined (and itself), not 0.
Practice
Challenge: Write safeSum(values) that adds only real, finite numbers from an array and skips undefined, null, NaN, strings and Infinity, returning the total and the count of skipped items.
Show solution
function safeSum(values) {
let total = 0;
let skipped = 0;
for (const v of values) {
if (Number.isFinite(v)) total += v;
else skipped++;
}
return { total, skipped };
}
console.log(safeSum([120, undefined, 85, null, NaN, "45", Infinity, 45]));{ total: 250, skipped: 5 }Key Takeaways
| Value | Test | Typical source |
|---|---|---|
undefined | x === undefined | Missing property or argument |
null | x === null | API or code says "empty" |
| Either | x == null | Optional data |
NaN | Number.isNaN(x) | Number("abc") |
Was this tutorial helpful?