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 JavaScript's 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 behavior comes from its early implementation.
In the original JavaScript implementation, values were represented internally using type tags.
The object type used a particular tag, while null was represented by a null pointer. Because of the way these internal representations worked, null was mistakenly identified as an object by the typeof operator.
That's why:
typeof null; // "object"
This historical behavior became part of JavaScript, and changing it now could break existing websites and applications.
For backward compatibility, JavaScript has kept this behavior.
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]"
Although 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:
nullis 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:
Top comments (0)