What is the difference between typeof and instanceof?

JavaScript Fundamentals Basic Fresher1–2 Yrs Conceptual 1 min read

Quick Answer

typeof returns a string for the primitive type ("string", "number", "boolean", "undefined", "function", "object", "symbol", "bigint"). instanceof checks whether an object is in a constructor's prototype chain (x instanceof Array). Quirks: typeof null === "object", typeof [] === "object" — use Array.isArray().

typeof gives you a string for the primitive type — "string", "number", "function". instanceof checks if an object was made by a particular constructor by walking its prototype chain. The famous quirks are typeof null being "object", which is a bug in the language, and typeof an array also being "object" — so for arrays I use Array.isArray. And instanceof is unreliable across iframes because each frame has its own Array constructor.

  • typeof is safe on undeclared variables (returns "undefined"), except in the TDZ.
  • instanceof breaks across execution contexts (iframes) because each has its own Array.
  • For a robust type tag: Object.prototype.toString.call(x) → "[object Array]", "[object Date]", etc.