The Curious Case of 'typeof null'

The Curious Case of 'typeof null'


let exampleObject = { key: "value" };

console.log(typeof null === typeof exampleObject); //true        


Have you ever wondered why typeof null returns 'object' in JavaScript? 🤔 It's a peculiar quirk that has puzzled many developers, myself included.

An Unchangeable Bug

Since the first release of ECMAScript, this behavior has been considered a bug. However, fixing it would break existing code, so it remains an unchangeable quirk of the language. But fear not, there's a logical explanation behind this seemingly odd behavior.

Understanding the Underlying Logic

In the early days of JavaScript, values were stored in 32-bit units consisting of a small type tag and the actual data. These type tags were stored in the lower bits of the units. For objects, the type tag was 000, indicating a reference to an object.

  • 000: object. The data is a reference to an object.
  • 1: int. The data is a 31-bit signed integer.
  • 010: double. The data is a reference to a double floating-point number.
  • 100: string. The data is a reference to a string.
  • 110: boolean. The data is a boolean.

The Mystery Unraveled

Here's where it gets interesting: null was considered a special value from the very beginning. It represented the null pointer, but in JavaScript, there were no pointers like in C. Instead, null simply meant nothing or void, represented by all zeros. Therefore, all 32 bits of null were zeros. When the JavaScript interpreter encounters null, it interprets the first three bits as the type "object." And that's why typeof null returns 'object'.


References : The history of “typeof null” (2ality.com)

Let's continue our journey of discovery in the captivating world of JavaScript! 💻🌐 #JavaScript #Programming #Development #Tech #LinkedInLearning



To view or add a comment, sign in

More articles by Srikanth K

Insights from the community

Others also viewed

Explore topics