JavaScript Reference ยท Operators
The instanceof operator
Reference for the JavaScript instanceof operator: prototype chain checks, Symbol.hasInstance, primitives, cross-realm pitfalls and alternatives.
The instanceof operator tests whether an object has a constructor's prototype somewhere in its prototype chain. It answers "was this object created by this class, or by a class that extends it?".
object instanceof Constructor
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
object instanceof Constructor
| Operand | Description |
|---|---|
object |
The value to test. Primitives always give false. |
Constructor |
A function or class (or an object with a Symbol.hasInstance method). |
Return value: true if Constructor.prototype appears in the prototype chain of object, otherwise false.
Exceptions: a TypeError if the right side is not an object, or is not callable and has no Symbol.hasInstance. A TypeError also occurs if the right side's prototype property is not an object.
Usage notes
- How it works: if
ConstructordefinesSymbol.hasInstance, that method decides. Otherwise the engine walksObject.getPrototypeOf(object)repeatedly and compares each link withConstructor.prototype. - Primitives are not instances.
"a" instanceof Stringisfalse; usetypeoffor primitives. - Replaced prototypes change the result. The check uses the constructor's current
prototype. - Multiple realms: an array created in another iframe is not
instanceofyourArray. UseArray.isArray()for arrays, or duck typing for other values. Object.create(null)objects have no chain, sox instanceof Objectisfalse.- Error handling:
catch (e) { if (e instanceof MyError) ... }is the standard way to branch on custom errors. - Alternatives:
Object.prototype.isPrototypeOf()works with plain prototype objects;intests for a property rather than lineage; brand checks with#field in objwork for private fields. - Not a type contract: two unrelated classes with the same shape are not interchangeable here.
Browser support
Supported in every browser and runtime. Symbol.hasInstance is part of ES2015 and is available in current browsers.
Related
- typeof
- in
- new
- Lessons: Prototypes, Inheritance, Classes