freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #48 of 61

typeof vs instanceof

LambdaVSThe Mutator
Lambda saystypeof checks primitive types; instanceof checks an object’s class/prototype chain.

typeof x returns a type string for primitives ("string", "number", "function") — but "object" for arrays, null, and most objects. To tell objects apart, use x instanceof Array (walks the prototype chain) or purpose-built checks like Array.isArray(x). Use the right tool for the right question.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleDistinguish an array from a plain object using Array.isArray and typeof.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const a=[1], o={};
document.getElementById('o').textContent='isArray(a)='+Array.isArray(a)+' isArray(o)='+Array.isArray(o);</script></body></html>
▶ Open the interactive comic issue
‹ Weakmap · Weakset · Gc-FriendlyTruthy / Falsy Gotchas ›