A note about ‘undefined’ in JavaScript

It turns out that undefined is not a JavaScript keyword, instead undefined is a global variable, which in browsers is defined as window.undefined.

It is not uncommon to see code that tests if a variable is undefined like this:

if (someObject.x === undefined) {
    // do something

Which is the same as writing

if (someObject.x === window.undefined) {
    // do something

If by some chance your window.undefined variable is modified then checks for undefined like this will fail. No sane developer would ever do this intentionally, but it may happen by accident causing hard to find bugs, like this:

var o = {};
window[o.name] = 'unknown'; // BLAM!, window.undefined is now a string

A better way to test for undefined is to use the typeof operator. Typeof an undefined variable will always return the string ‘undefined’.

// Good way to test for undefined
if (typeof someObject.x === 'undefined') {
    // do something

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s