null vs undefined in JavaScript: the difference

By

Understand the difference between null and undefined in JavaScript, two primitive types, how to check for each, and why typeof null returns 'object'.

~~~

Let’s talk about the similarities first.

null and undefined are JavaScript primitive types. Both represent the absence of a value, and both are falsy: they behave as false where a boolean is expected.

The difference is intent.

The meaning of undefined is to say that a variable has been declared, but it has no value assigned. It is the language’s own “nothing here yet”. You also get undefined when you read an object property that does not exist, or when a function returns without a return statement.

null, instead, is a value you assign on purpose. It says “this is intentionally empty”. JavaScript never sets a variable to null on its own.

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 defined error, but this does not mean it’s undefined.

How to check for each

How do you check if a variable is null? Use the comparison operator, for example age === null

Same for undefined: age === undefined

In both cases, you can check for:

if (!age) {

}

and this will be matching both null and undefined.

Watch out though: !age also matches 0, the empty string, NaN and false. If 0 is a legitimate value for age, this check silently treats it as missing — a classic bug. When you want to match only null and undefined, use loose equality against null:

if (age == null) {
  //true for null and undefined, false for 0 or ''
}

This is one of the very few places where == instead of === is the right call, because null == undefined is true and nothing else compares equal to them.

typeof and the historical bug

You can also use the typeof operator:

let age
typeof age //'undefined'

although null is evaluated as an object, even though it is a primitive type:

let age = null
typeof age //'object'

That 'object' result is a bug from the very first version of JavaScript. Fixing it would break existing websites, so it is still with us. Don’t use typeof to detect null: compare with === null instead.

~~~

Related posts about js: