Why does typeof null return "object" in JavaScript?
It is a bug from the first version of JavaScript: values carried a type tag, and null used the same tag as objects. Fixing it would break old websites, so it stays. Check for null with value === null.
Explain it simply
Imagine a college register where every student's roll number starts with a branch code. By mistake, the "no student" placeholder was given the same code as Computer Science. Years later, thousands of documents depend on that code, so nobody can change it. typeof null is that placeholder.
In the original JavaScript engine, values were stored with a small type tag. Objects had tag 0, and null was represented as a null pointer, which was also all zeros. So typeof read the tag and reported "object". A proposal to fix it was rejected because too much existing code relied on the old behaviour.
Example
const user = null;
console.log(typeof user); // Output: object
console.log(user === null); // Output: true
// A safe "is this a real object?" check
function isObject(value) {
return typeof value === "object" && value !== null;
}
console.log(isObject(null)); // Output: false
console.log(isObject({ name: "Asha" })); // Output: trueWhat to say in the interview
"typeof null is 'object' because of how the first engine tagged values: objects used tag zero, and null was the zero pointer. It is a known bug that can't be fixed without breaking the web. So when I need to detect null, I use strict equality, value === null, and when I need a real object I check typeof value === 'object' && value !== null."
Common mistakes
- Writing
if (typeof x === "object")and then reading a property, which crashes whenxisnull. - Assuming null is actually an object. It is a primitive.