typeof null is "object"
typeof null returns "object" because of a bug in the first version of JavaScript that can never be fixed without breaking the web. Check for null with === null.
What it means
In the original implementation, values carried a type tag and null used the same tag as objects. The behaviour was kept for compatibility. So a check like typeof x === "object" lets null through, and then x.property throws.
Common causes
1. Checking for an object with typeof
null passes the check.
Breaks
if (typeof value === "object") {
return value.id; // crashes on null
}Works
if (value !== null && typeof value === "object") {
return value.id;
}2. Describing a value's type
null needs its own case before typeof.
Breaks
return typeof value;Works
if (value === null) return "null";
if (Array.isArray(value)) return "array";
return typeof value;How to find it in your own code
Test null explicitly with value === null (or value == null to catch undefined too), and arrays with Array.isArray, before relying on typeof.
Try it: fix this bug
harddescribeType(null) returns "object" instead of "null".
function describeType(value) {
if (typeof value === "object") {
return "object";
}
return typeof value;
}Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.