Why typeof null Returns "object" in JavaScript

·

2 min read

In JavaScript, one of the quirks that has puzzled developers for decades is the fact that:

console.log(typeof null); // Outputs: "object"

This behavior is often described as a "historical bug" in the language, and understanding why this happens requires a look into JavaScript's early days and its type system.

The Basics of typeof

The typeof operator in JavaScript is used to determine the type of a value. It returns a string indicating the type, such as:

“number” for numbers

“string” for strings

“boolean” for booleans

“undefined” for undefined values

“object” for objects (including arrays and null)

At first glance, the classification of null as an "object" seems inconsistent with its intended purpose of representing the intentional absence of any object value. So, why does this happen?

The Historical Bug

The roots of this behavior can be traced back to the earliest implementation of JavaScript in 1995. At that time, JavaScript's values were represented internally using a type tag stored in the lower bits of their binary representation. Here is a simplified explanation of how these tags worked:

  • Objects: Represented by the binary tag 000.

  • Null: Represented by the NULL pointer in memory, which was also internally tagged as 000.

Because both objects and null shared the same tag (000), the typeof operator could not distinguish between them and returned "object" for null values.

Why wasn’t it Fixed?

When JavaScript gained popularity, this behavior became widely relied upon in existing codebases. Fixing it would have introduced breaking changes to millions of websites and applications. To maintain backward compatibility, the behavior was preserved.

Modren Approaches to Handle null

While the behavior of typeof null cannot be changed without breaking backward compatibility, developers have devised other ways to check for null explicitly. Here are a few common approaches:

Direct Comparison

The simplest way to check if a value is null is by comparing it directly:

if (value === null) { console.log("The value is null"); }

Using Object.prototype.toString

For a more general approach to type checking, you can use:

if (Object.prototype.toString.call(value) === "[object Null]") { console.log("The value is null"); }

Avoiding Overuse of typeof

Given its quirks, typeof should be used with care. For example, avoid relying on it for distinguishing between null and objects.

Conclusion

The typeof null quirk serves as a reminder of JavaScript’s rapid origins and the compromises made to ensure its widespread adoption. While it’s easy to see this as a flaw, it’s also a testament to the importance of backward compatibility in web development. By understanding the reasons behind such quirks, developers can navigate them effectively and write clearer, more intentional code.