In JavaScript undefined
can be reassigned, so it is often advised to create a self executing function that assures undefined is actually undefined. As an alternati
Because JavaScript has both values. And while other languages may only have nil
/null
JavaScript grew up with undefined
being the "unknown value" while null
is clearly a known value to represent nothing.
Compare var x
where x
is undefined because no value has been assigned and var y = null
where y
is null
. It was set to something -- a sentential representing "nothing". This core fundamental usage of undefined
vs null
in JavaScript runs very deep and other cases include:
delete
'd) property also yield undefined
and not null
(it would result in null
only if null
had been assigned).undefined
.undefined
returned from standard functions like getElementById
Thus, in Javascript, it is often more correct to use undefined
and not null
. They both represent different things. A library that tries to fight this is fighting JavaScript.
Happy coding.
Personally, in almost all cases I avoid an explicit check for undefined
or null
. I believe that in most -- but not all -- cases all false values should be equivalent and that it is the callers responsibility to conform to the public contract stated.
Because of this belief I would consider the comparison x == null
on the verge of trying to guard too much and yet too little, but in the case of catching null
or undefined
, it works, as pointed out. Go start a trend ;-)