The question isn’t really “why is there a null value in JS” – there is a null value of some sort in most languages and it is generally considered very useful.
The question is, “why is there an undefined value in JS”. Major places where it is used:
- when you declare
var x;
but don’t assign to it,x
holds undefined; - when your function gets fewer arguments than it declares;
- when you access a non-existent object property.
null
would certainly have worked just as well for (1) and (2)*. (3) should really throw an exception straight away, and the fact that it doesn’t, instead of returning this weird undefined
that will fail later, is a big source of debugging difficulty.
*: you could also argue that (2) should throw an exception, but then you’d have to provide a better, more explicit mechanism for default/variable arguments.
However JavaScript didn’t originally have exceptions, or any way to ask an object if it had a member under a certain name – the only way was (and sometimes still is) to access the member and see what you get. Given that null
already had a purpose and you might well want to set a member to it, a different out-of-band value was required. So we have undefined
, it’s problematic as you point out, and it’s another great JavaScript ‘feature’ we’ll never be able to get rid of.
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?
Yes. Keep undefined
as a special value for signaling when other languages might throw an exception instead.
null
is generally better, except on some IE DOM interfaces where setting something to null
can give you an error. Often in this case setting to the empty string tends to work.