JavaScript has not one, but two different values that mean "nothing." This confuses people, so let's clear it up.
undefinedmeans "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.nullmeans "this is empty on purpose." JavaScript never setsnullby 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."
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"or42). - A holder with just an empty cardboard tube: that's something like
0or"". 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.