JavaScript has two ways of saying “there is no value here”. They are not the same.
undefined: nobody gave it a value
JavaScript uses undefined when something has not been set. You will meet it often:
let a;
console.log(a); // → undefined
const user = { name: "Maya" };
console.log(user.email); // → undefined (no such property)
function greet(name) {
console.log(name); // → undefined (no argument was passed)
}
greet();
function noReturn() {}
console.log(noReturn()); // → undefined (nothing returned)
null: someone chose “empty”
null is a value you assign to say “this is intentionally empty”.
let selectedUser = null; // nobody selected yet
console.log(selectedUser); // → null
selectedUser = { name: "Maya" };
A common use: an API returns null when it knows there is no result.
Comparing them
console.log(undefined === null); // → false
console.log(undefined == null); // → true (loose equality treats them as equal)
console.log(typeof undefined); // → undefined
console.log(typeof null); // → object
The last line is a famous historical bug: typeof null returns "object", but null is a primitive. It cannot be fixed without breaking old websites.
Checking for “no value”
function describe(value) {
if (value === undefined) return "undefined";
if (value === null) return "null";
return "has a value";
}
console.log(describe()); // → undefined
console.log(describe(null)); // → null
console.log(describe(0)); // → has a value
Notice that 0 counts as a value. Do not use a plain if (!value) when 0 or "" are valid. The operator ?? in Nullish Coalescing handles exactly this case.
Rule of thumb
undefined. Use null yourself only when you want to say “empty on purpose”.