The typeof null

JavaScript has been evolving for decades, and one of its most surprising legacy effects is that typeof null produces the string "object".

Loading TypeScript...

This is a bug - a remnant from the very first version of JavaScript - and one that unfortunately cannot be fixed without breaking an unknown multitude of existing programs. This strange behavior, which suggests that a null value is actually an object, is codified in the ECMAScript standard which determines the uniform way in which JavaScript code is interpreted.

History of JavaScript

When JavaScript was first created in the mid-90s, values were represented internally using type tags, which were stored as a few bits of information in memory. More specifically, values were represented by 32 bits of information, and the top 1 - 3 bits would contain a small tag that described the data type.

  • If the top bit was 1, the remaining 31 bits contained a signed integer
  • Otherwise (the top bit is 0):
    • If the next 2 bits were 00, the remaining 29 bits were a reference to an object
    • If the next 2 bits were 01, the remaining data is a floating point number
    • If the next 2 bits were 10, the data is a reference to a string
    • If the next 2 bits were 11, the data is a boolean

There were two special values:

  • undefined was the integer $100$

Objects had a type tag of 0, and null was represented as a null pointer (i.e. a nonexistent reference to a location in the computer's memory). However, null also got the same type tag of 0, which caused typeof to treat the null pointer as an object.

Because this behavior made it into the official ECMAScript specification and a lot of code started depending on this behavior, changing it would break existing sites and functionality across the Internet. Thus, it remains.

Other typeof quirks

Since you're learning this typeof quirk, you might as well explore them all.

Loading TypeScript...

Was this page helpful?