开发者

Is there anything wrong with using 'var undefined' to test for undefined

Is there anything wrong with this test for undefi开发者_StackOverflowned?

var undefined;

if(x == undefined){
    //do something
}

or this:

function undefined(x){
    return typeof x == 'undefined';
}

if(undefined(x)){
    //do something
}

jsLint doesn't throws a reserverd word error, but the code still seems to work...


Don't redefine undefined.

Other programmers expect undefined to always be undefined, not a function for function's sake.

People often use typeof operator to ensure a reference error is not thrown when used to test for variables that are undefined.

If anyone ever does this to you, you can use...

undefined = void 0;

... to revert it back.


As undefined isn't a Javascript keyword, there's nothing wrong with it per se.

However, you're overriding a core variable that's used frequently for checking undefined variables in your second example to be a function. I'd shriek and ban that person as a committer if I saw that in anyone's code that I was reviewing.


undefined is just a default property of the global object, which you can override/redefine. That's why you should always test for undefined using typeof x == 'undefined', since the typeof operator cannot be redefined.

var undefined;

if(x == undefined){
    //do something
}

What happening here is that you're defining a new variable called "undefined", which you don't assign a value and which hence gets the valued undefined. x is not defined either and also has a value of undefined. Hence both are equal. It's rather pointless though.


undefined is not a reserved word in JavaScript (ECMA-262). It is a named constant of type Undefined;

By declaring:

var undefined;

you declare variable with the same name in local scope.

So technically you can do this, just don't define something like this:

var undefined = 13;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜