instanceof — a walk up the prototype chain, and where it fails¶
Level: 301 · for anyone who has used instanceof to check a type
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: x instanceof C only asks whether C.prototype is on x's prototype chain, so it is false for a primitive and for an array made in another realm, changes when C.prototype is replaced, and Symbol.hasInstance lets C answer anything.
Keywords: instanceof, Symbol.hasInstance
What the finished page will answer¶
- What do
'text' instanceof Stringandnew String('text') instanceof Stringprint, and what should you use for primitives instead? - Why is an array made by
vm.runInNewContext('[]')notinstanceof Array, and what doesArray.isArraysay about it? - What happens to
obj instanceof FafterF.prototypeis replaced, and why does assigning to a class'sprototypethrow? - What does
Object.create(null) instanceof Objectprint, and why? - How does a static
[Symbol.hasInstance]method change the answer, and what doesFunction.prototype[Symbol.hasInstance]do by default? - What does
tscreport for a primitive on the left ofinstanceof?
Examples it will need¶
-
instanceof_chain_walk_js.js— instanceof for a primitive, a wrapper object, Object.create(null), and an instance whose constructor's prototype was replaced afterwards -
instanceof_other_realm_js.js— an array and an Error made in a node:vm context, tested with instanceof, Array.isArray and Error.isError -
instanceof_primitive_tserror.ts— tsc's TS2358 error for a primitive on the left of instanceof
See also¶
- The prototype chain — the chain instanceof walks
typeof— the check for primitives that instanceof cannot make- Narrowing — instanceof as a type guard in TypeScript
- Well-known symbols — the other hooks that sit beside Symbol.hasInstance
- Arrays — the array test that works across realms