Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 328
Ryokel Avatar asked Aug 13 '26 17:08

Ryokel


1 Answers

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.

like image 119
kaz Avatar answered Aug 15 '26 07:08

kaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!