null and undefined
Nothing, two ways.
Most languages have one way to say nothing here. JavaScript has two. Undefined, and null. They're similar, but they mean slightly different things.

- One way to say nothing?
- JavaScript has two
- undefined and null
Two empty values
A variable that's created, but never given a value, is undefined. That's JavaScript saying, nothing was put here. Null is a value you set on purpose, to say, this is intentionally empty. Run it. Both are empty, but they're not exactly equal.
let middleName;
console.log("not set:", middleName);
let selectedItem = null;
console.log("cleared:", selectedItem);
console.log(null === undefined);not set: undefined cleared: null false
When you see them
You'll see undefined when you read a property that doesn't exist, or call a function that doesn't return anything. You use null yourself, when you want to clear a value, like no item selected. Checking for them is so common that modern JavaScript has special operators for it, which we'll meet later.
| key | value |
|---|---|
| undefined | never set |
| null | set to empty on purpose |
| Missing property | undefined |
| Clear a value | use null |
Checking for empty values
A common job is checking whether a value is missing. Comparing with null using two equals catches both null and undefined, which is one of the rare good uses of two equals. And the two question marks operator gives a fallback, only for null or undefined. Run it.
let nickname;
let middleName = null;
const age = 0;
console.log(nickname == null, middleName == null, age == null);
console.log(nickname ?? "no nickname");
console.log(age ?? "no age");true true false no nickname 0
Summary
Undefined means no value was ever set, and null means empty on purpose. Next, checking a value's type with typeof.
Key takeaways- undefined: not set
- null: empty on purpose
- null !== undefined