In JavaScript, there are two values which basically say 'I don't exist' - undefined
and null
.
A property to which a programmer has not assigned anything will be undefined
, but in order for a property to become null
, null
must be explicitly assigned to it.
I once thought that there was a need for null
because undefined
is a primitive value and null
an object. It's not, even if typeof null
will yield 'object'
: Actually, both are primitive values - which means neither undefined
nor null
can be returned from a constructor function, as both will be converted to an empty object (one has to throw an error to proclaim failure in constructors).
They also both evaluate to false
in boolean contexts. The only real difference I can think of is that one evaluates to NaN
, the other to 0
in numeric contexts.
So why is there both undefined
and null
if this just confuses programmers who are incorrectly checking for null
when trying to find out whether a property has been set or not?
What I'd like to know is if anyone has a reasonable example where it's necessary to use null
which couldn't be expressed using undefined
instead.
So the general consensus seems to be that undefined
means 'there is no such property' while null
means 'the property does exist, but holds no value'.
I could live with that if JavaScript implementations would actually enforce this behavior - but undefined
is a perfectly valid primitive value, so it can easily be assigned to existing properties to break this contract. Therefore, if you want to make sure if a property exists, you have to use the in
operator or hasOwnProperty()
anyway. So once again: what's the practical use for separate values for undefined
and null
?
I actually use undefined
when I want to unset the values of properties no longer in use but which I don't want to delete
. Should I use null
instead?