TryBugHunt

typeof null is "object"

typeof null is "object" in JavaScript means 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.

JavaScriptPattern: Null and undefined errors

How do I fix typeof null is "object"?

In JavaScript, typeof null returns "object" because of a bug in the first version of the language that was kept for compatibility. So typeof x === "object" lets null through, and x.id then throws. Check value !== null && typeof value === "object", and use Array.isArray() for arrays.

  1. 1. typeof object checksEvery typeof x === "object" needs x !== null in front of it before reading properties.
  2. 2. Test null firstUse value === null, or value == null to catch both null and undefined.
  3. 3. Arrays are objects tootypeof [] is also "object". Use Array.isArray(value) to tell arrays apart.

What does typeof null is "object" mean?

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.

Why does typeof null is "object" happen?

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

hard

describeType(null) returns "object".

function describeType(value) {
    if (typeof value === "object") {
        return "object";
    }
    return typeof value;
}
Open with hintsRuns in your browser. No account needed.

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.