DEV Community

Cover image for Why typeof null === "object" in JavaScript? A Deep Dive into a Quirky Bug
MO Slah
MO Slah

Posted on

Why typeof null === "object" in JavaScript? A Deep Dive into a Quirky Bug

If you’ve ever played around with JavaScript and used typeof, you may have stumbled upon this strange behavior:

typeof null; // returns "object"

Wait—what? Shouldn’t typeof null return "null"?

This is one of the most well-known and long-standing oddities in JavaScript. Let’s take a deep dive into why this happens, how it originated, and why it will likely never be fixed.

What Is typeof in JavaScript?

The typeof operator in JavaScript returns a string that represents the type of the operand:

typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof {}; // "object"
typeof function(){}; // "function"
typeof Symbol(); // "symbol"

But then:
typeof null; // "object"
That looks... wrong.

Why Does typeof null Return "object"?

This dates back to the early days of JavaScript, in the 1990s. JavaScript was designed in a hurry—literally in just 10 days—and the internal implementation details left some quirks behind.

Here’s the technical reason:

Internally, JavaScript values were represented using a type tag in their binary form.

The type tag for objects was 000, and null also happened to be represented with a binary value of all zeroes (0x00).

As a result, the typeof operation interpreted null as an object.

So it’s essentially a bug in the original implementation that got locked into the language.

Why Can’t This Be Fixed?

It seems simple—just fix the bug so that typeof null returns "null", right?

Not quite.

Here’s the problem: JavaScript is the most widely used programming language in the world, and it’s embedded in billions of websites and applications. Changing the return value of typeof null now would break backward compatibility for existing codebases that depend on it returning "object".

In fact, this issue is so well-known that Brendan Eich (the creator of JavaScript) addressed it himself, admitting it’s a bug but also saying it’s too late to fix.

Here’s a relevant quote:

“typeof null === "object" is a bug, but fixing it would break a lot of code on the web.”

— Brendan Eich, Creator of JavaScript

Summary

  • typeof null returns "object" — a historical bug.

  • It originated from early binary representations of types.

  • It’s too risky to fix now because it would break too much existing code.

  • Use strict equality to check for null.

Final Thoughts

JavaScript is full of quirks, and this one is a classic example. While it might seem strange at first, understanding these “gotchas” helps us write more robust and reliable code.

Top comments (0)