By Rahul — Google Frontend Engineer
typeof — Checking Primitive Types
typeof returns a string indicating the type of the operand. It works on the value itself, not the prototype chain.
The null Bug
typeof null === "object" is a bug from the first version of JavaScript (1995). It was never fixed because too much existing code depends on it. Always check for null explicitly:
instanceof — Checking the Prototype Chain
instanceof checks whether the prototype of a constructor appears anywhere in the prototype chain of an object.
When Each Fails
typeof Cannot Distinguish Objects
instanceof Fails Across Realms
Real Production Issues
- Cross-iframe instanceof: We had a component library that checked
error instanceof Error. Errors thrown from an iframe failed this check. We switched to duck-typing:error && typeof error.message === 'string' - Bundler duplicates: If two versions of a library are bundled,
instanceoffails because there are two different constructor functions
The Better Approach: Object.prototype.toString
This works across realms and gives precise type information.
Best Practices
- Use
typeoffor primitives (string, number, boolean, undefined) - Use
Array.isArray()for arrays - Use
instanceofonly when you control both the constructor and the usage context - For libraries, prefer duck-typing over instanceof
Summary
typeof checks the value type but has the null bug and cannot distinguish objects. instanceof walks the prototype chain but breaks across iframes and bundler duplicates. Use the right tool for the right situation.