Should I use typeof in Javascript type equality?

What's better?

if (obj === undefined) { } 

vs.

 if (typeof(obj) === 'undefined') { } 
+4
source share
4 answers

If you somehow cannot refrain from shadowing global undefined or cannot but try to refer to undeclared variables, use:

 typeof x === 'undefined' 

If you adhere to good coding rules and believe that you allow code breaking, use:

 x === undefined 

If you want another alternative, you can use:

 x === void 0; 

... where void always returns undefined and does not rely on a global property.

Another protection you can use is to use the shadow image in a good way, defining the correct undefined in the function:

 (function( undefined ) { // notice that no arguments were passed, // so the `undefined` parameter will be `undefined` var x; if( x === undefined ) { } })(); 

... some people prefer to use a different name:

 (function( undef ) { // notice that no arguments were passed, // so the `undefined` parameter will be `undefined` var x; if( x === undef ) { } })(); 
+4
source

I would go with the second one, since "undefined" is not a reserved word. Example:

 var obj = undefined; undefined = {}; if(obj === undefined) { console.log("undefined 1"); } if(typeof obj === 'undefined') { console.log("undefined 2"); } 

Only β€œundefined 2” will show, because the undefined variable can be changed.

+1
source

This was asked earlier, but a more general approach is to do this:

  typeof(x) == 'undefined' 

See: JavaScript: undefined! == undefined?

-1
source

I use

 if(typeof x==="undefined"){ } 

Why? Because the code below does not work on the iPad.

 if( x===undefined){ } 

iOS reports an error that x is undefined. :-) You cannot use undefined vars for comparison in iOS

-1
source

All Articles