back home

blog

typeof null === 'object', and other JavaScript apologies

Every JavaScript developer eventually finds out — usually mid-debug — that typeof null returns 'object'. It looks like a bug. It is a bug. It has been a bug for thirty years and will still be a bug thirty years from now.

you can verify this in any browser console. or any node repl. or any spec-compliant runtime.

The reason is that the very first JavaScript implementation stored values as 32-bit words with a low-bit type tag — the bottom three bits told you whether the word was an integer, a double, a string, an object, or one of a few singletons. The tag 000 meant "object pointer." And the null pointer, conveniently, was all zeros.

So when typeof read the type tag from a null reference, it saw 000, looked up the table, and confidently returned 'object'. No one noticed until it was too late to change.

most modern engines no longer use this exact representation, but they all preserve the behavior because the web depends on it.

The proposed fix that wasn't

In 2010, someone proposed for ES6 that typeof null should return 'null'. It would have been one line in the spec. The proposal was withdrawn after about a week of discussion: too much code in the wild already branched on typeof x === 'object' assuming null would quietly pass through.

fixing it would have broken a lot of feature-detection code that no one was paid to update.

So we live with it. x === null is the only correct null check. typeof is one of those JavaScript features that looks like a function but is really a frozen snapshot of an implementation decision from 1995.

Bonus apologies

A non-exhaustive list of other things JavaScript would do differently if it could:

  • NaN !== NaN — true, and the only value with this property
  • [] + [] returns "", but [] + returns "[object Object]"
  • parseInt("08") used to return 0 in older browsers because the leading zero was read as octal
  • Math.max() with no arguments returns -Infinity (this one is actually correct, just surprising)
most of these would be fine in a do-over. none of them will ever change.

The lesson, if there is one, is that compatibility is a one-way ratchet on the open web. Every quirk that ships becomes a contract you can't break, and after thirty years you end up with a few historical decisions cemented into every engine in the world.