Ryokel
Ryokel

Reputation: 80

Set a variable undefined and null

I just read some code and i see this line:

var foo = null, undefined;

When i test the variable it is both null and undefined.

Thus my question, What is the purpose to set a variable both null and undefined ? I don't get it. Thank you for the explanation.

Upvotes: 3

Views: 85

Answers (3)

Sami
Sami

Reputation: 8419

Short: That's useless

without assigning anything a variable is undefined. You can assign null to make it null. However your comparison also matters

Fiddle Demo

if(foo == null) //true
    alert('1');
if(foo == undefined) //true
    alert('2');

Now strict comparison having ===

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');

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173572

The purpose of that statement is to have a local declaration of undefined in a variable with the same name.

For example:

// declare two local variables
var foo = null, undefined;

console.log(foo === undefined); // false

It's similar to:

function test(foo, undefined)
{
    console.log(foo === undefined); // false
}
test(null); // only called with a single argument

This isn't typically necessary because a sane browser will not allow anyone to redefine what undefined means and jslint will complain about this:

Reserved name 'undefined'.

Basically, I would recommend not doing this at all:

var foo = null;

Btw, the above declaration is not to be confused with using the comma operator in this manner:

var foo;

foo = 1, 2;
console.log(foo); // 2

Upvotes: 0

kaz
kaz

Reputation: 1190

As mentioned in the comments, you are likely not testing foo in the correct manner, a variable cannot be both undefined and null.

var foo = null, undefined;
alert(foo); //shows null
alert(typeof foo); //shows object (not undefined)

So what's going on? The comma indicates that you are declaring an additional variable. Since undefined is a keyword already, this particular 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.

Upvotes: 2

Related Questions