Why typeof null === "object" in JavaScript Is Not a Bug You Can Fix
If you’ve been writing JavaScript for any length of time, chances are you’ve come across this puzzling behavior:
typeof null; // "object"
At first glance, this seems like a blatant bug—and you’re not wrong. But it’s more complicated than that. This behavior is one of JavaScript’s most infamous quirks, and understanding the reason behind it will help you write safer, more intentional code.
Why Does This Happen?
The story goes back to the early 1990s, when JavaScript was created in a rush (just 10 days). In the original implementation, JavaScript values were represented as type-tagged references. Each type was given a numeric tag:
- Objects: tag
0
- Integers, floats, strings, etc. had other tags
The value null
was implemented as a null pointer, which—coincidentally—also had the binary representation of 0
.
So, when typeof
checked the tag, it saw 0
and assumed it was an object. That design decision was never corrected, because by the time it was widely noticed, too much code depended on this behavior.
Is It Still a Bug?
Technically, yes. But officially, it’s not considered a bug anymore. It’s part of the ECMAScript specification and will remain that way to avoid breaking legacy applications.
How Should You Check for null
Then?
Instead of relying on typeof
, use strict equality:
if (value === null) {
// This is the right way to check for null
}
Need to check for objects but exclude null
? Do this:
if (typeof value === 'object' && value !== null) {
// This is a real object, not null
}
How Does typeof
Behave for Other Values?
Here’s a quick overview of typeof
results:
typeof undefined // "undefined"
typeof true // "boolean"
typeof 42 // "number"
typeof "hello" // "string"
typeof Symbol("id") // "symbol"
typeof function() {} // "function"
typeof {} // "object"
typeof [] // "object" (arrays are objects)
typeof null // "object" (this is the quirky one)
Other Considerations
- Arrays are also
"object"
withtypeof
. To detect an array, useArray.isArray(value)
. typeof
is not reliable for deep type-checking. It’s best for basic primitives.
If you need stronger type detection, consider using Object.prototype.toString.call(value)
:
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call([]); // "[object Array]"
Finally
The fact that typeof null === "object"
is a historical accident, but one that JavaScript has embraced for the sake of backward compatibility. As a developer, the key is to understand the nuance and use the right tools (=== null
, Array.isArray
, or Object.prototype.toString.call
) depending on what you’re checking.
JavaScript isn't perfect—but knowing its quirks makes you a better programmer.
Comments ()