Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Is there anything wrong with this test for undefined?

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

like image 599
Mark Brown Avatar asked Dec 09 '22 08:12

Mark Brown


2 Answers

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.

like image 54
alex Avatar answered Dec 29 '22 01:12

alex


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.

like image 36
Demian Brecht Avatar answered Dec 29 '22 01:12

Demian Brecht