Categories
javascript undefined

How can I check for “undefined” in JavaScript? [duplicate]

2893

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?

10

3087

If you are interested in finding out whether a variable has been declared regardless of its value, then using the in operator is the safest way to go. Consider this example:

// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"

But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in operator for a more robust check.

"theFu" in window; // true
"theFoo" in window; // false

If you are interested in knowing whether the variable hasn’t been declared or has the value undefined, then use the typeof operator, which is guaranteed to return a string:

if (typeof myVar !== 'undefined')

Direct comparisons against undefined are troublesome as undefined can be overwritten.

window.undefined = "foo";
"foo" == undefined // true

As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.

if (window.myVar) will also include these falsy values, so it’s not very robust:

false
0
""
NaN
null
undefined

Thanks to @CMS for pointing out that your third case – if (myVariable) can also throw an error in two cases. The first is when the variable hasn’t been defined which throws a ReferenceError.

// abc was never declared.
if (abc) {
    // ReferenceError: abc is not defined
} 

The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,

// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", { 
    get: function() { throw new Error("W00t?"); }, 
    set: undefined 
});
if (myVariable) {
    // Error: W00t?
}

27

  • 8

    @Anurag, the third case will throw a ReferenceError if myVariable is not declared

    Aug 2, 2010 at 18:12

  • 5

    @Anurag, you’re welcome, since you talk about ES5, maybe is worth mentioning that undefined is now described as non-writable, non-configurable and non-enumerable. So, window.undefined = "omg"; will simply fail silently or throw under strict mode.

    Aug 2, 2010 at 18:23

  • 9

    Can “typeof” be redefined?

    Aug 2, 2010 at 19:09

  • 7

    typeof is a language statement, it cannot be redefined any more than if/else/while/for/function etc. could be.

    – MooGoo

    Aug 2, 2010 at 19:31

  • 70

    undefined is immutable in modern browsers. Setting window.undefined does nothing.

    – Paul S.

    Nov 22, 2012 at 17:06

1456

+500

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

24

  • 58

    It’s marginally more likely that undefined could be redefined, just because people do use it for such checks. Some people habitually put the constant on the left-hand side when doing such checks: if (undefined == someVariable). It only takes a typo for this to silently redefine undefined: if (undefined = someVariable).

    – Tim Down

    Aug 2, 2010 at 20:16


  • 61

    I never write code that has undefined on the LHS. Even if I did, the fact that I use === instead of == makes the typo extremely unlikely. But the fact that == is incorrect is more of a worry. In any case, a bug like that is usually easy to find. Kind of like this bug: typeof x == "undefned".

    Dec 1, 2011 at 16:20


  • 42

    How could this be upvoted 41 times, it simply doesn’t work. If myVar is indeed undefined the code will throw an error, and it’s easy to test – jsfiddle.net/WcM5g The proper way is typeof myVar === 'undefined'.

    – laurent

    Jul 11, 2013 at 13:31


  • 43

    @Laurent: A joke right? This assumes the variable was declared in some way or the other, such as by a var keyword or a function parameter. I would sell my soul before I (intentionally) wrote code that tried acting on undeclared variables in any which way. Remember, undeclared and undefined are two different concepts in JS.

    Jul 11, 2013 at 18:18


  • 14

    @Andy In C (and C++), it is both common and good practice to reverse operands like that, to avoid typos. if (NULL = myVar) fails to compile and is instantly caught, whereas if (myVar = NULL) creates a bug that may be difficult to track down depending on what other code is around it. Modern compilers should give you a warning, but many experienced C programmers have already developed the habit of swapping the order.

    Feb 15, 2016 at 20:15

327

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
}

9

  • 20

    You might want to check if a particular global variable representing a piece of functionality has already been defined. For example, library code may wish to check that the library has not already previously been included.

    – Tim Down

    Aug 2, 2010 at 20:20

  • 1

    ‘xyz’ in window or ‘xyz’ in self are much better

    Jun 28, 2013 at 17:44


  • 5

    @JamiePate: Just to be clear, I disagree that 'xyz' in window is a better answer than typeof xyz == "undefined" because it is testing the wrong thing. The in operator checks for the existence of a property, regardless of its value, while the question at least appears to be asking how to test if the value of a variable is undefined. Perhaps a better example for me to choose would have been var foo; "foo" in window; this returns true while foo is definitely undefined.

    – Tim Down

    Jun 29, 2013 at 8:55

  • 1

    @JamiePate: Why is xyz === undefined better than typeof xyz == "undefined"? Agreed about globals, but of the two of us only you have been recommending checking properties of window.

    – Tim Down

    Jul 10, 2013 at 8:56

  • 6

    It’s redundant in most cases (and less readable). If you know xyz is a declared variable, why go through the extra trouble? Type checking and string comparison are much slower in some browsers, so if you do it a lot in a tight loop you will lose some performance. jsperf.com/type-of-undefined-vs-undefined/6

    Jul 10, 2013 at 17:25