Bayu’s sorting cabinet: typeof picks one of 8 drawers, instanceof walks the prototype chain. Arrays from another iframe included. An interactive typeof vs…
A wrong type check is a bug at run time. typeof [] === "object" makes people take an array for a plain object, typeof null === "object" lets null through, and an array from another iframe fails instanceof Array. Knowing when to use typeof, instanceof or a special tool is truly defensive code.
typeof for primitives, instanceof for objects
typeof x === "object" is also true for null and arrays, not only plain objects For a plain object, use x !== null && typeof x === "object" && !Array.isArray(x).instanceof Array Every iframe has its own Array, so the prototype differs. Array.isArray() is immune to this."hi" instanceof String turns out to be false Plain text is a primitive, not a wrapper object. For primitives, use typeof x === "string".[1, 2, 3]: typeof says "object" An array is an object. typeof cannot tell it apart; Array.isArray() can.null: the object drawer (an old mistake) Since 1995, and it will never be fixed. Check for null with x === null.new Date() with {a: 1} Both are typeof "object", but instanceof Date tells them apart. That is what instanceof is for.() => {} The one object with a typeof drawer of its own: "function".