Values and variables
null vs undefined in JavaScript: the difference
Understand the difference between null and undefined in JavaScript, two primitive types, how to check for each, and why typeof null returns 'object'.
null and undefined both mean “no useful value”, but they arrive for different reasons.
Both are JavaScript primitive types. Both are falsy in boolean context.
The difference is intent.
undefined means the language never got a value. A declared variable with no assignment is undefined. A missing object property is undefined. A function with no return gives undefined.
null is a value you assign on purpose. It says “empty by design”. JavaScript never sets null for you.
let age //age is undefined
let age = null //age is null
Note: accessing a variable that’s not been declared will raise a
ReferenceError: <variable> is not definederror, but this does not mean it’sundefined.
How to check for each
Test for null with strict equality:
age === null
Test for undefined the same way:
age === undefined
A loose check catches both:
if (age == null) {
//true for null and undefined, false for 0 or ''
}
This is one of the few places where == beats ===, because null == undefined is true and nothing else compares equal to both.
Watch out with !age. It also matches 0, '', NaN, and false. If 0 is a valid age, you silently treat it as missing. That is a classic bug.
When you need only null and undefined, prefer age == null over !age.
typeof and the historical bug
typeof on an uninitialized variable returns 'undefined':
let age
typeof age //'undefined'
typeof null returns 'object':
let age = null
typeof age //'object'
That 'object' result is a bug from the first JavaScript release. Fixing it would break old sites, so it remains. Do not use typeof to detect null. Compare with === null instead.
Run both checks in the console on null, undefined, and {}. The results stick in memory faster than reading about them.
Lesson completed