[javascript] How can I check for "undefined" in JavaScript?

What is the most appropriate way to test if a variable is undefined in JavaScript?

I've seen several possible ways:

if (window.myVariable)

Or

if (typeof(myVariable) != "undefined")

Or

if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?

This question is related to javascript undefined

The answer is


In this article I read that frameworks like Underscore.js use this function:

function isUndefined(obj){
    return obj === void 0;
}

2020 Update

One of my reasons for preferring a typeof check (namely, that undefined can be redefined) became irrelevant with the mass adoption of ECMAScript 5. The other, that you can use typeof to check the type of an undeclared variable, was always niche. Therefore, I'd now recommend using a direct comparison in most situations:

myVariable === undefined

Original answer from 2010

Using typeof is my preference. It will work when the variable has never been declared, unlike any comparison with the == or === operators or type coercion using if. (undefined, unlike null, may also be redefined in ECMAScript 3 environments, making it unreliable for comparison, although nearly all common environments now are compliant with ECMAScript 5 or above).

if (typeof someUndeclaredVariable == "undefined") {
    // Works
}

if (someUndeclaredVariable === undefined) { 
    // Throws an error
}

I personally use

myVar === undefined

Warning: Please note that === is used over == and that myVar has been previously declared (not defined).


I do not like typeof myVar === "undefined". I think it is long winded and unnecessary. (I can get the same done in less code.)

Now some people will keel over in pain when they read this, screaming: "Wait! WAAITTT!!! undefined can be redefined!"

Cool. I know this. Then again, most variables in Javascript can be redefined. Should you never use any built-in identifier that can be redefined?

If you follow this rule, good for you: you aren't a hypocrite.

The thing is, in order to do lots of real work in JS, developers need to rely on redefinable identifiers to be what they are. 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.

(If you are still scared of undefined being redefined, why are you blindly integrating untested library code into your code base? Or even simpler: a linting tool.)


Also, like the typeof approach, this technique can "detect" undeclared variables:

if (window.someVar === undefined) {
    doSomething();
}

But both these techniques leak in their abstraction. I urge you not to use this or even

if (typeof myVar !== "undefined") {
    doSomething();
}

Consider:

var iAmUndefined;

To catch whether or not that variable is declared or not, you may need to resort to the in operator. (In many cases, you can simply read the code O_o).

if ("myVar" in window) {
    doSomething();
}

But wait! There's more! What if some prototype chain magic is happening…? Now even the superior in operator does not suffice. (Okay, I'm done here about this part except to say that for 99% of the time, === undefined (and ****cough**** typeof) works just fine. If you really care, you can read about this subject on its own.)


Personally, I always use the following:

var x;
if( x === undefined) {
    //Do something here
}
else {
   //Do something else here
}

The window.undefined property is non-writable in all modern browsers (JavaScript 1.8.5 or later). From Mozilla's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined, I see this: One reason to use typeof() is that it does not throw an error if the variable has not been defined.

I prefer to have the approach of using

x === undefined 

because it fails and blows up in my face rather than silently passing/failing if x has not been declared before. This alerts me that x is not declared. I believe all variables used in JavaScript should be declared.


You can use typeof, like this:

if (typeof something != "undefined") {
    // ...
}

Update 2018-07-25

It's been nearly five years since this post was first made, and JavaScript has come a long way. In repeating the tests in the original post, I found no consistent difference between the following test methods:

  • abc === undefined
  • abc === void 0
  • typeof abc == 'undefined'
  • typeof abc === 'undefined'

Even when I modified the tests to prevent Chrome from optimizing them away, the differences were insignificant. As such, I'd now recommend abc === undefined for clarity.

Relevant content from chrome://version:

  • Google Chrome: 67.0.3396.99 (Official Build) (64-bit) (cohort: Stable)
  • Revision: a337fbf3c2ab8ebc6b64b0bfdce73a20e2e2252b-refs/branch-heads/3396@{#790}
  • OS: Windows
  • JavaScript: V8 6.7.288.46
  • User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36

Original post 2013-11-01

In Google Chrome, the following was ever so slightly faster than a typeof test:

if (abc === void 0) {
    // Undefined
}

The difference was negligible. However, this code is more concise, and clearer at a glance to someone who knows what void 0 means. Note, however, that abc must still be declared.

Both typeof and void were significantly faster than comparing directly against undefined. I used the following test format in the Chrome developer console:

var abc;
start = +new Date();
for (var i = 0; i < 10000000; i++) {
    if (TEST) {
        void 1;
    }
}
end = +new Date();
end - start;

The results were as follows:

Test: | abc === undefined      abc === void 0      typeof abc == 'undefined'
------+---------------------------------------------------------------------
x10M  |     13678 ms               9854 ms                 9888 ms
  x1  |    1367.8 ns              985.4 ns                988.8 ns

Note that the first row is in milliseconds, while the second row is in nanoseconds. A difference of 3.4 nanoseconds is nothing. The times were pretty consistent in subsequent tests.


I use it as a function parameter and exclude it on function execution that way I get the "real" undefined. Although it does require you to put your code inside a function. I found this while reading the jQuery source.

undefined = 2;

(function (undefined) {
   console.log(undefined); // prints out undefined
   // and for comparison:
   if (undeclaredvar === undefined) console.log("it works!")
})()

Of course you could just use typeof though. But all my code is usually inside a containing function anyways, so using this method probably saves me a few bytes here and there.


Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/

(Note that the use of var for in tests make a difference when in a scoped wrapper)

Code for reference:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

And results:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined

    var x;
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    if (typeof y === "undefined") {
        alert ("I am not even declared.")
    };

    /* One more thing to understand: typeof ==='undefined' also checks 
       for if a variable is declared, but no value is assigned. In other 
       words, the variable is declared, but not defined. */

    // Will repeat above logic of x for typeof === 'undefined'
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    /* So typeof === 'undefined' works for both, but x === undefined 
       only works for a variable which is at least declared. */

    /* Say if I try using typeof === undefined (not in quotes) for 
       a variable which is not even declared, we will get run a 
       time error. */

    if (z === undefined) {
        alert ("I am neither declared nor defined.")
    };
    // I got this error for z ReferenceError: z is not defined 

The most reliable way I know of checking for undefined is to use void 0.

This is compatible with newer and older browsers, alike, and cannot be overwritten like window.undefined can in some cases.

if( myVar === void 0){
    //yup it's undefined
}

if (typeof foo == 'undefined') {
 // Do something
};

Note that strict comparison (!==) is not necessary in this case, since typeof will always return a string.


Since none of the other answers helped me, I suggest doing this. It worked for me in Internet Explorer 8:

if (typeof variable_name.value === 'undefined') {
    // variable_name is undefined
}

// x has not been defined before
if (typeof x === 'undefined') { // Evaluates to true without errors.
   // These statements execute.
}

if (x === undefined) { // Throws a ReferenceError

}

On the contrary of @Thomas Eding answer:

If I forget to declare myVar in my code, then I'll get myVar is not defined.

Let's take a real example:

I've a variable name, but I am not sure if it is declared somewhere or not.

Then @Anurag's answer will help:

var myVariableToCheck = 'myVar';
if (window[myVariableToCheck] === undefined)
    console.log("Not declared or declared, but undefined.");

// Or you can check it directly 
if (window['myVar'] === undefined) 
    console.log("Not declared or declared, but undefined.");

If it is undefined, it will not be equal to a string that contains the characters "undefined", as the string is not undefined.

You can check the type of the variable:

if (typeof(something) != "undefined") ...

Sometimes you don't even have to check the type. If the value of the variable can't evaluate to false when it's set (for example if it's a function), then you can just evalue the variable. Example:

if (something) {
  something(param);
}