undefined and null: Two Kinds of Nothing

Grade 2, page 8 of 13. A one-minute read.

JavaScript has not one, but two different values that mean "nothing." This confuses people, so let's clear it up.

  • undefined means "no value has been given yet." It's what JavaScript puts in a box automatically when you create a variable but don't fill it. You've seen this already in Grade 1.
  • null means "this is empty on purpose." JavaScript never sets null by itself. It's a value that you, the programmer, choose to put in a box, to say "I know this is empty, and that's intentional."
JavaScript
let middleName;
const spouse = null;

console.log(middleName);
console.log(spouse);

It prints

undefined
null
Think of it like thisThe toilet paper holder

Picture a toilet paper holder on the bathroom wall:

  • A holder with a fresh roll on it: that's a value (like "hello" or 42).
  • A holder with just an empty cardboard tube: that's something like 0 or "". There's something there, but it's empty.
  • A holder with nothing on it at all, because someone deliberately took the tube away: that's null. Empty on purpose.
  • No holder on the wall, because nobody has installed one yet: that's undefined.

When should you use null? Whenever you want to say "there's deliberately no value here right now." For example, a game might have let winner = null; at the start, because nobody has won yet, and then later set winner = "Sofia"; when someone does.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning