How to check for undefined in JavaScript

An initial value of a variable that is not given a value is undefined. if it is declared.

How do you determine if JavaScript is unable to define a value in JavaScript?

The short answer

In modern browsers you can easily compare the variable with undefined

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

Some people disagree with comparing undefined to define because the old browsers made it possible to assign its value again like this.

undefined = "test"

After that reselection, undefined directly could no longer be used to verify if a variable was given a value.

This behavior was however corrected in 2009 using ECMAScript 5

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 }.

Modern browsers do not allow the re-assignment of undefined global values.

What if I need to support IE8 and older?

Comparing directly with undefined is generally safe. There is no practical reason to request a re-assignment for undefined.

Thomas Eding provides a compelling example.

I don’t hear people telling me that I shouldn’t use setTimeout because someone can

window.setTimeout = function () {
    alert("Got you now!");
};

Bottom line, the “it can be redefined” argument to not use a raw === undefined is bogus.

You can still be concerned if you don’t know the answer.

To obtain the value for undefined, you could use the void operator. This works even if you have a global  window.undefined  value has already been written:

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

The zero in this case doesn’t mean anything special; you can just use  1  and  function(){}void(anything), always evaluates to undefined.

Alternativly you can use “typeof” to check if the value was assigned. Instead of comparing to a global undefinedvalue you check if it is the type “undefined”.

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

This is slightly more complicated than the previous options. Even though the name wasn’t explicitly declared, typeof would still declare that it’s undefined. An undeclared variable would not be compared to undefined,  void(0). Instead, it would produce a ReferenceError.

But don’t use void(0) directly

In code, avoid using typeof x === "undefined"  or  void(0). These expressions are not self-explanatory so they should be wrapped with an isUndefined function, such as the following:

function isUndefined(value){
    // Obtain `undefined` value that's
    // guaranteed to not have been re-assigned
    var undefined = void(0);
    return value === undefined;
}

This functionality is already available in many utility libraries. For example, Underscore.js contains an _.isUndefined function.

Exit mobile version