Why it is right for null to be of type object in Javascript

I’m really amazed how many articles you can find about how stupid it is that typeof null returns object in Javascript. Many people feel that this is wrong since null basically means “not currently an object”.

The mistake here is thinking that a variable with type object actually holds an object. It’s a simple mistake to make, but one that will bite you times and times again:

A variable of type object actually means object-pointer. Unlike primitive types which have more less a direct value, these variables don’t actually hold a value itself, just a non-exclusive pointer to an object. That pointer is their value.

That’s also why objects are apparently passed by reference to functions: While they are actually passed by value, the passed value is the pointer.

If you look at it like this, it actually seems kind of bizarre that typeof null could return anything but object. After all it is still a pointer, just a pointer that points nowhere.

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.