Undefined, Null and NaN

Updated · 7 min read
mediumES2026javascriptundefinednullnaninterview

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 without return.
  • 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 as Number("abc"). Its type is "number".
  • Test with x === undefined, x === null, x == null (either one) and Number.isNaN(x).
  • Use ?? and ?. to handle null and undefined; validate numbers to keep NaN out.

Side by Side

undefinednullNaN
MeaningNo value givenDeliberately emptyFailed number
typeof"undefined""object""number"
Set byJavaScript, automaticallyCode, on purposeFailed arithmetic or conversion
Equal to itself (===)YesYesNo
Number(x)NaN0NaN
In JSONProperty is omittednullBecomes null
Correct testx === undefinedx === nullNumber.isNaN(x)
FalsyYesYesYes

undefined: Never Assigned

undefined.js▶ Try it
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]);
Output
undefined
undefined
undefined
undefined
undefined

Every 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":

null.js▶ Try it
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));
Output
null
null
null
null

The 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

tests.js▶ Try it
const values = [undefined, null, 0, "", false, NaN];
 
for (const v of values) {
  console.log(String(v).padEnd(9), v === undefined, v === null, v == null);
}
Output
undefined true false true
null      false true true
0         false false false
          false false false
false     false false false
NaN       false false false

Explanation: 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:

handling.js▶ Try it
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);
Output
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":

nan.js▶ Try it
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));
Output
NaN
false
true
true -1
NaN

Explanation: 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:

json.js▶ Try it
const data = { a: undefined, b: null, c: NaN, list: [undefined, null, NaN] };
console.log(JSON.stringify(data));
Output
{"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:

clean.js▶ Try it
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);
  }
}
Output
Navika: $120 (check)
Advitha: no amount yet
Bad amount for Zoe: 12x

Common 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
puzzle.js▶ Try it
console.log(null + 1, undefined + 1, typeof NaN, null == 0, undefined == null);
Output
1 NaN number false true

null 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
safe-sum.js▶ Try it
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]));
Output
{ total: 250, skipped: 5 }

Quick check: undefined, null and NaN

3 questions
1What does a function without a return statement return?
2Which check is true for both null and undefined, but false for 0 and ""?
3What does JSON.stringify({ a: undefined, b: NaN }) produce?

Key Takeaways

ValueTestTypical source
undefinedx === undefinedMissing property or argument
nullx === nullAPI or code says "empty"
Eitherx == nullOptional data
NaNNumber.isNaN(x)Number("abc")

Was this tutorial helpful?

Lesson 53 of 139