Skip to content
Tutorials Center
My learning

Topics

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?".

JavaScript
object instanceof Constructor

Try it

JS Classes and inheritance

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Custom checks and errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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 Constructor defines Symbol.hasInstance, that method decides. Otherwise the engine walks Object.getPrototypeOf(object) repeatedly and compares each link with Constructor.prototype.
  • Primitives are not instances. "a" instanceof String is false; use typeof for primitives.
  • Replaced prototypes change the result. The check uses the constructor's current prototype.
  • Multiple realms: an array created in another iframe is not instanceof your Array. Use Array.isArray() for arrays, or duck typing for other values.
  • Object.create(null) objects have no chain, so x instanceof Object is false.
  • 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; in tests for a property rather than lineage; brand checks with #field in obj work 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.