null, undefined & NaN

JavaScript has three different ways to say 'nothing'. Learn the critical differences between these absence values.

JavaScript5 min readConcept 8 of 62

The three absences

undefined means a variable has been declared but has not yet been assigned a value. It is JavaScript's default state of 'nothingness'.

null is an assignment value. It means you are intentionally stating that a variable holds 'nothing' or is 'empty'.

NaN stands for 'Not-a-Number'. It is the result of a mathematical operation that failed or an invalid type conversion (e.g. trying to divide a word by 2).

Why have both null and undefined?

Having two empty values is one of JavaScript's most criticized design flaws, but it can be useful. undefined usually means the system or engine hasn't provided a value yet. null means the programmer explicitly set the value to be empty.

By keeping this convention, you can look at a variable and immediately know if it's empty because you made it empty (null), or empty because you forgot to initialize it (undefined).

How to check for them

To check for null or undefined, always use strict equality (=== null). Do not use loose equality (==), because null == undefined evaluates to true!

Checking for NaN is uniquely difficult because NaN === NaN is actually false. NaN is the only value in JavaScript that is not equal to itself.

To reliably check if a value is NaN, use the built-in Number.isNaN(value) method.

The Nothingness Matrix

Observe how these three empty values behave differently when compared, checked for type, or used in math.

The Three Absences

// 1. undefined: "I haven't been given a value yet"
let user;
console.log(typeof user);
// 2. null: "I have intentionally been emptied"
user = null;
console.log(typeof user); // (The legacy bug!)
// 3. NaN: "I tried to do math and failed"
const score = "hello" / 2;
console.log(typeof score); // (Ironically numeric)
console.log(score === NaN); // Never equal to itself
Console Output
>"undefined"
>"object"
>"number"
>false
iAlways use Number.isNaN(value) to check for NaN, since strict equality (===) fails on it!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the result of `NaN === NaN`?
  2. 2Which value indicates that a variable has been declared but not assigned?
  3. 3What does `typeof NaN` return?

Remember this

  • undefined means uninitialized. null means intentionally empty.
  • NaN === NaN is always false. Use Number.isNaN() instead.
  • typeof null is 'object' and typeof NaN is 'number'.

Done with this concept?

Mark it complete to track your progress. No login needed.