Why Does typeof null Return "object"?

As you learn JavaScript you will likely run into some odd behaviour:

 console.log(typeof null); 

Output:

 object 

Wait a minute... isn't null supposed to mean nothing?

So why is JavaScript saying it's an object?

This is one of JavaScripts oldest and most well known quirks! Let's look at what is happening.

What is null?

In JavaScript null is an intentional lack of value.

An example would be:

 let user = null; console.log(user); // null 

Here we are saying that user has no value.

If we check the type of user:

 console.log(typeof user); 

We get:

 object 

Interesting.

History

JavaScript was created in 1995 and this is a result of how it was originally implemented.

Values were stored with type tags.

Objects had a certain type tag whereas null was stored as a null pointer.

This resulted in null being recognised as an object.

Therefore:

 typeof null; // "object" 

This is just a mistake that got added in.

Could they just change it?

Unfortunately if this was changed now it would cause issues with current code on the web so it has been kept for backwards compatibility.

Is null really an object?

No.

null is a primitive value.

For example:

 console.log(typeof null); // "object" console.log( Object.prototype.toString.call(null) ); // "[object Null]" 

Whilst the typeof returns "object", it is not an object.

There are many other interesting typeof results:

 console.log(typeof []); // "object" console.log(typeof {}); // "object" console.log(typeof null); // "object" console.log(typeof undefined); // "undefined" 

Don't assume all values that return "object" are the same.

How should you check for null?

This is where the quirk comes in.

Don't use typeof. Instead use strict equality:

 let user = null; if (user === null) { console.log("User is null"); } 

This is straightforward.

If you want to check for both null and undefined you can use:

 if (user == null) { console.log("Value is missing"); } 

This is one of those times where you would deliberately use ==.

Remember

JavaScript is full of interesting quirks.

Every time you see:

 typeof null // "object" 

Remember:

  • null is a primitive value.

  • It is not an actual object.

  • It is due to the original implementation of JavaScript.

  • It is kept for backwards compatibility.

Sometimes the quirkiest parts of JavaScript have the most interesting history!

Have you ever been confused by typeof null? What other quirks have you found in JavaScript?

Let me know in the comments!

Sources:

MDN - typeof operator

MDN - null