BACK

Check for undefined in JavaScript

2 min read

If you write JavaScript regularly, you've likely needed to check whether a variable is undefined.

But, what is the best way to do it?

The intuitive way

Any programmer experienced in other languages will intuit:

if (x === undefined) { ... }

This works without problems--almost.

Direct comparison with undefined works in all modern browsers. Old browsers, however, allowed reassignment:

undefined = "new value";

With this reassignment, direct comparison fails.

ECMAScript 5 fixed this in 2009:

15.1.1.3 undefined
The value of undefined is undefined (see 8.1). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

The “safe” way

If you support old browsers and worry about undefined reassignment, use alternative methods.

Reading the type

The typeof operator returns "undefined" for undefined values:

if (typeof x === "undefined") { ... }

Note: typeof does not throw an error for undeclared variables.

Using void

The void operator also returns undefined:

if (x === void(0)) { ... }

The zero has no special meaning. As MDN states:

The void operator evaluates the given expression and then returns undefined.

Which way is better

As a consultant, I learned the best answer: it depends. Here are some tips.

Follow existing codebase conventions. For new code running only on modern browsers, use direct comparison--it's clear and readable even for JavaScript beginners. For old browser support, create an isUndefined function with your preferred method inside. This expresses intent clearly.