Masterbook/Chapter 20• 2 min read
View Raw Code on GitHub

Difference between undefined, null, and NaN

Difference between undefined, null, and NaN

In JavaScript, all three - undefined, null, and NaN - represent "absence" in some form. But they describe different kinds of absence, and mixing them up often causes confusion.
Think of them like this:

undefined -> "The variable exists, but no one has given it a value yet."

null -> "I deliberately set this to nothing."

NaN -> "I tried to get a number, but the result is nonsense."

Let's explore these one by one.

  1. undefined - value not assigned, is the default state of things that exist but haven't been assigned any value. You don't have to explicitly write undefined; JavaScript gives it automatically in several cases:
  • Declared but not initialized variable
  • Missing function return value
  • Accessing a non-existent object property
  • Function parameter not passed during a call

Examples:

let x;
console.log(x); // undefined (declared but no value)
function doSomething() {}
console.log(doSomething()); // undefined (no return statement)
const user = { name: "Alice" };
console.log(user.age); // undefined (property doesn't exist)
function greet(name) {
  console.log("Hello " + name);
}

greet(); // name is undefined
So undefined is JavaScript's way of saying:

"This thing is real, but it doesn't currently hold a value."
undefined often happens unintentionally - when something is missing or not yet set.

  1. null - intentional absence, represents a value that's intentionally empty. developers assign null themselves to mean, "This should have no value."
Example:
let selectedUser = null; // means: no user selected yet

Unlike undefined, which JavaScript assigns automatically, null is assigned by you when you want to signal "nothing here on purpose." Some real use cases:

  • Resetting a variable:
    user = null; // clear previous user
  • Placeholder for future object values:
let result = null;
if (dataFound) result = process(data);

Indicating "not applicable" or "no result."

Even though null means "nothing," it's still a valid JavaScript value and must be assigned explicitly.

The typeof null oddity
typeof null; // "object"

This is a bug in JavaScript's design that dates back to the earliest versions. It was never fixed for backward compatibility. But it doesn't mean that null is an object - it's just an old quirk. To correctly check for null, always use:

value === null;