DEV Community

LaurenTyson🕶
LaurenTyson🕶

Posted on

JavaScript typeof null likes to play tricks

As a newbie coder, everything is confusing. I'm always like, wait - what? That was precisely my thought when I asked JavaScript typeof null, and it told me object.

shows typeof examples in node

Huh?

If null is an object, and objects are a collection of properties, that would mean null has some value. But we know that's not true; therefore, this is JavaScript playing a trick on us. Let's break down why.

Null isn't an object.

Null is just, null. In JavaScript, null is a structured root primitive value. It stands by itself. It's the absence of value, unlike undefined which is an empty value—two different things.

Then why does JavaScript return object? Because according to MDN, JavaScript values are represented as a type tag and a value, and the type tag for objects is 0 thus lumping null in as an object.

As we can imagine, representing the absence of value is tricky; as an aside, in other programming languages, null is represented as the null pointer 0x00. Reference.

In an effort to fix this bug, in 2015, when JavaScript went through its rework it was proposed to change to typeof null === null. Unfortunately, that fix was rejected, but honestly, for a good reason. ES Wiki, the web archive for the ECMAScript programming language, says:

"This proposal has been rejected. It was implemented in V8 but it turned out that it broke a lot of existing sites. In the spirit of One JavaScript this is not feasible."

Check out the ES Wiki page I'm referencing, the full explanation is fascinating.

Since developers have always known of the typeof null bug, many people wrote their code to account for it. And while the proposed fix would have fixed our brains, it would have broken our apps.

So now we newbies know of this bug too! Don't let this break your brain as it did mine. It's just one of the many fascinating oddities of JavaScript programming.

Top comments (0)