Interview FAQ: typeof null

Known as the most notorious bug in JavaScript, this special case of typeof usage is popping up in JavaScript interviews in one form or another more often than you’d think.

It all comes down to figuring out what typeof null returns.

We go into this knowing that typeof is a JavaScript operator which inspects the type of a given value and returns a string representing that type. We also know what JavaScript’s types are:

  • undefined
  • boolean
  • number
  • string
  • object
  • symbol (added in ES6)
  • null

Now, if we apply typeof to values of the first six types, we get the predicted behaviour, i.e. the strigified names of their types.

typeof undefined === "undefined"; //true
typeof true === "boolean"; //true
typeof 42 = "number"; //true
typeof "42" = "string"; //true
typeof { x: 1 } === "object"; //true
typeof Symbol() === "symbol"; //true (in ES6)

So perhaps we’d expect something along the lines of typeof null === "null" to be true as well. But in fact, the typeof operator behaves in a special, unexpected way where null is concerned.

typeof null === "object"; //true

Of course that the correct return would have been “null”, and the existing behaviour is indeed a bug, and one that has been part of JavaScript for no less than twenty years or so. Unfortunately, there is too much content out there relying on this very bug, so it’s unlikely that it will ever be fixed. Even more of a reason to keep it in mind, then!

One can still test a value null based on its type via a compound condition:

var x = null;

(!x && typeof x === "object"); //true

That’s it! Kill those interviews, peeps!