What's the difference between
var myvar;
and
var myvar = null;
?
I've just seen both next to next in professional code and wondering what this is all about...
What's the difference between
var myvar;
and
var myvar = null;
?
I've just seen both next to next in professional code and wondering what this is all about...
One creates myvar
(in the current scope) and assigns no value to it (leaving it === undefined
).
The other assigns null
to it too.
The assignment of null
may be significant depending on how other code interacts with the variable. OTOH, it may done for lack of understanding of what it means.
If you try var myvar;
you've defined myvar
as undefined that means it simply has not been assigned a value.
but when you try var myvar = null;
you've assigned the null literal to the myvar
,which means that the variable represents the null, empty, or non-existent reference.
I prefer to use var myvar = null;
Why?
If I'm checking to see if that value is set in the future, null means that it has not been set, where as undefined means that there was probably an error while trying to set myvar
somewhere in the code.
Heres some other opinions as well - What reason is there to use null instead of undefined in JavaScript?