Why is typeof null "object"?
A bug from 1995 that can't be fixed, and the difference between null and undefined.
typeof null answered "object". But null means "empty" — how is that an object? It isn't. It's a bug. The most famous bug in JavaScript — and it's over thirty years old.In 1995 Brendan Eich wrote the first version of JavaScript for the Netscape browser — in ten days, as the legend goes. Inside the engine, every value was stored together with a small type tag: a few bits (zeros and ones) at the start. Objects had the tag 000.
And null was stored as the "null pointer" — an address made entirely of zeros. When typeof looked at its tag, it saw 000 and honestly answered: "object". Nobody added a special check for null.
console.log(typeof null);
console.log(typeof {});
console.log(typeof undefined);
console.log(typeof "text");null is the only "empty" value that pretends to be an object.Why wasn't it fixed? People tried. While a new version of the standard was being prepared, someone proposed making typeof null return "null". The proposal was rejected: over the years, millions of sites had written code that relies on "object". The fix would break them — and the first rule of the web is don't break what already works. So JavaScript's old mistakes aren't fixed; they're documented.
Why have two kinds of "nothing" at all? They mean different things:
let middleName;
console.log(middleName); // not filled in yet
const selected = null; // on purpose: nothing selected
console.log(selected);
const cat = { name: "Byte" };
console.log(cat.age); // no such propertyundefined; a programmer says null.typeof is great for numbers, strings and true/false, but ask null directly. And don't be ashamed of your bugs — JavaScript has one that's protected like a listed building.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.