Lesson 92 +15 XP

Undefined and NaN

Undefined and NaN

Two special values you will meet often.

undefined

A variable with no assigned value is undefined:

let x;
console.log(x); // undefined

Also returned by missing object properties.

null

null is an intentional empty value. It means "nothing here on purpose":

let x = null;

undefined vs null

  • undefined: no value was ever set.
  • null: the value was explicitly set to "nothing".

NaN

NaN means "Not a Number". It results from invalid math:

"abc" * 2; // NaN
Number("abc"); // NaN

Checking NaN

NaN is the only value not equal to itself. Use Number.isNaN():

NaN === NaN;          // false (surprise!)
Number.isNaN(NaN);    // true
Number.isNaN("abc");  // false ("abc" is not NaN)

TL;DR

  • undefined means no value was assigned.
  • null is an intentional empty value.
  • NaN results from invalid math.
  • Use Number.isNaN() to check NaN.