Something is wrong using "var undefined" to check for undefined

Is there something wrong with this test for undefined?

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

or that:

 function undefined(x){ return typeof x == 'undefined'; } if(undefined(x)){ //do something } 

jsLint does not throw a reserverd word error, but the code still works ...

+4
javascript
May 20 '11 at 1:52 AM
source share
4 answers

Do not override undefined .

Other programmers expect that undefined will always be undefined , not a function for a function.

People often use the typeof operator to ensure that a reference error does not occur when using undefined variables for checking.

If someone does this with you, you can use ...

 undefined = void 0; 

... to bring him back.

+7
May 20 '11 at 2:00
source share
— -

Since undefined not a Javascript keyword , there is nothing wrong with it.

However, you override the main variable, which is often used to check for undefined variables in the second example as a function. I would cry out and forbid this person as a committer if I saw this in any code that I looked at.

+5
May 20 '11 at 2:01 a.m.
source share

undefined is just the default property of a global object that you can override / override. This is why you should always test undefined with typeof x == 'undefined' , since the typeof operator cannot be overridden.

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

What happens here is that you are defining a new variable called "undefined" that you are not assigning a value to and therefore getting an undefined value. x also not defined, and also has the value undefined . Therefore, both are equal. This is pretty pointless.

+1
May 20 '11 at 2:00
source share

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

Declaring:

 var undefined; 

you are declaring a variable with the same name in the local scope.

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

 var undefined = 13; 
+1
May 20 '11 at 2:05 a.m.
source share



All Articles