开发者

Should I use typeof in Javascript type equality?

开发者 https://www.devze.com 2023-03-15 05:35 出处:网络
What开发者_开发技巧 is better? if (obj === undefined) { } vs. if (typeof(obj) === \'undefined\') { }

What开发者_开发技巧 is better?

if (obj === undefined) { }

vs.

if (typeof(obj) === 'undefined') { }


If you somehow can't refrain from shadowing the global undefined, or can't keep from trying to reference undeclared variables, then use:

typeof x === 'undefined'

If you adhere to good coding practices, and believe in letting broken code break, use:

x === undefined

If you want a different alternative, you can use:

x === void 0;

...where void always returns undefined, and doesn't rely on the global property.

Another safeguard you can use is to use shadowing in a good way by defining a proper undefined in a 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 give it a different name:

(function( undef ) {

    // notice that no arguments were passed, 
    // so the `undefined` parameter will be `undefined`

    var x; 

    if( x === undef ) {

    }

})();


I would go with the second one, as "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");   
}

Will only show "undefined 2" because the variable undefined can be changed.


This has been asked before, but the more common approach is to do this:

     typeof(x) == 'undefined'

See: JavaScript: undefined !== undefined?

0

精彩评论

暂无评论...
验证码 换一张
取 消