Check for undefined in javascript - should typeof be used or not?

I am a bit confused about how best to check if a variable is undefined or not in javascript. I did it like this:

myVar === undefined; 

But is it better to use typeof in all cases?

 typeof myVar === undefined; 

What about using undefined vs "undefined" , which I also saw?

+7
source share
3 answers

This is the best way to check - completely reliable:

 typeof myVar === "undefined" 

This is normal, but it may fail if someone unhelpfully overwrites the global value undefined :

 myVar === undefined; 

It should be said that ECMAScript 5 states that undefined is read-only, so the above will always be safe in any browser that matches.

This will never work, because it compares "undefined" === undefined (different types):

 typeof myVar === undefined; 
+14
source

This test will always work as expected:

 typeof a === 'undefined' 

Since the value undefined can be changed, such tests are not always reliable:

 a = {} ab === undefined 

In these cases, you can test instead of void 0 :

 ab === void 0 // true 

However, this will not work for single variable tests:

 a === void 0 // <-- error: cannot find 'a' 

You can get around this by testing against window.a , but it is preferable to use the first method.

+2
source

I believe that in the most common cases, for example, when checking whether a parameter passed through a function, myVar === undefined sufficient, since myVar will always be declared as a parameter

0
source

All Articles