The thing about programming languages is, they aren't facts of the universe, they were made by people, sometimes very quickly. This means that they are often full of little quirks and oddities. Some cause problems, some don't, some we can fix, and some we have to learn to live with.
One such example is what some would call the typeof null bug.
So what am I talking about? In JavaScript, there are primitive values, and objects. Most value types fall under the heading of primitive, such as Number, String, Boolean, Null, and Undefined. An object, on the other hand, is more complex, being typically thought of as a collection of properties.
Null is a primitive value, and has only the one possible value: null. But take a look at the following code, and make a guess about what it would output:
let x = null
console.log(typeof x, x === null)
Based on what I've said above, you would likely expect to see null, true
. typeof
returns the value type, and ===
strictly evaluates equality. x is null, so we'd expect to get null, and true.
Logical. Unfortunately, what you actually get is object, true
.
That's right, null
is an object... But doesn't that seem off?
Well, this is due to a quirk of the way null was defined in the early days of JavaScript, and can’t be altered at this point. It comes down to the way the creators of JavaScript defined types, and how this interacted with common representations for NULL on most platforms. This post sums it up nicely:
In the first implementation of JavaScript, values were represented in two parts - a type tag and the actual value. There were 5 type tags that could be used, and the tag for referencing an object was 0. The null value, however, was represented as the NULL pointer, which was 0x00 for most platforms. As a result of this similarity, null has the 0 type tag, which corresponds to an object.
The upshot of all this is, if you're writing a function and you need to check whether or not a value is null, you’ll need to use the ===
operator, not typeof
, if you want to get accurate results.
While I confess to lacking a great deal of the context for why this happened, it fascinates me that it did. I love getting little glimpses into the past that clear up why things are the way they are today. Sure, it may cause some confusion and I may grumble when it causes a hitch in my programming, but it helps me remember that ultimately, everything we do we do as people, in conversation with people past and present. Maybe I'm sappy, but as a social psych major I just think that's neat.
Top comments (0)