How can I check for "undefined" in JavaScript?

ID : 227

viewed : 119

Tags : javascriptundefinedjavascript

Top 5 Answer for How can I check for "undefined" in JavaScript?

vote vote


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? } 
vote vote


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(); } 


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

vote vote


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


You can use typeof, like this:

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


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

Top 3 video Explaining How can I check for "undefined" in JavaScript?