What is the difference between typeof and instanceof?
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.
typeofis safe on undeclared variables (returns"undefined"), except in the TDZ.instanceofbreaks across execution contexts (iframes) because each has its ownArray.- For a robust type tag:
Object.prototype.toString.call(x)→"[object Array]","[object Date]", etc.