Null is not an Object

James Falola
Hacktive Devs
Published in
2 min readFeb 21, 2020
console output for typeof null
console output for typeof null

Hi there! if you’re a bit familiar with JavaScript, the code below is probably not news to you.

> typeof null
'object'

Yes! In JavaScript, typeof null returns ‘object’. Then you start to wonder “why?”, since null means “nothing”. As a developer, my instinct has always been “Well, everything is an object in JS” until I got to think, well, not everything is an object as we have primitive data types in Javascript.

What are Primitive data types?

These are data types that are immutable and they do not have their own methods. Immutable because there’s no way to change their values once they’re created. Primitive data types include:
1. String (characters in-between “ ”)
2. Number (Integers, Floats…)
3. Null (nothing)
4. Undefined (not defined)
5. Boolean (true or false)
6.
Symbol (Newly introduced in ES6)

If you’re wondering why .length works on a string, you should check Autoboxing in Javascript. You can use typeof operator to check data type in JavaScript.

What is null?
In English, null means having no value.

In Js, null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.

So why would null be considered an object?

This is simply a bug in Javascript dated as far back as when JavaScript was first released. Wondering why it hasn’t been fixed? This, as well as other bugs in JavaScript, would break a lot of existing codebase and libraries if they get fixed, so we just go with the flow.

I think it is too late to fix typeof. The change proposed for typeof null will break existing code.Douglas Crockford

In the earlier version of JavaScript, values are stored in 32 bits, where the first 3 bits indicate the data type and the rest represents the value. For an object, the first three bits are 000. Null in JavaScript means nothing or void so it gets represented as all 0. Hence, the weird bug.

Hopefully, this brought you some sort of clarity. This is one of those articles you didn’t know you needed but comes in handy. 👋 Bye!

--

--