Set variable undefined and null
I just read some code and I see this line:
var foo = null, undefined;
When I check the variable, it is null and undefined.
So my question is: What is the purpose of setting a variable to both null and undefined? I do not understand. Thanks for the explanation.
As mentioned in the comments, you probably won't be testing foo properly, the variable cannot be undefined or undefined .
var foo = null, undefined;
alert(foo); //shows null
alert(typeof foo); //shows object (not undefined)
So what's going on? The comma means that you are declaring an additional variable. Since undefined is already a keyword, this part of the statement has no effect. However, if you did it like this:
var foo = null, undefined1;
alert(foo); //shows null
alert(typeof foo); //shows object (not undefined)
alert(undefined1); //shows undefined
alert(typeof undefined1); //shows undefined
You can see that you are actually declaring a new variable undefined1
that has no initial value.
The purpose of this statement is to have a local declaration undefined
in a variable of the same name.
For example:
// declare two local variables
var foo = null, undefined;
console.log(foo === undefined); // false
He looks like:
function test(foo, undefined)
{
console.log(foo === undefined); // false
}
test(null); // only called with a single argument
This is usually not required because a sane browser won't let anyone override what it means undefined
, and jslint will complain about this:
The reserved name is 'undefined'.
Basically, I would recommend not doing this at all:
var foo = null;
Btw, the above expression should not be confused with using a comma like this:
var foo;
foo = 1, 2;
console.log(foo); // 2
Short: It's useless
without assigning anything to the variable undefined
. You can assign null
to make it null. However, your comparison also matters
Screenshot Demo
if(foo == null) //true
alert('1');
if(foo == undefined) //true
alert('2');
Now a strict comparison with ===
if(foo === null) //false............can be true if assigned to null
alert('3');
if(foo === undefined) //true.......can be flase if assigned to null
alert('4');