Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

instanceof

Checks whether an object was created by a class (or a subclass).

Available since: ES3

Syntax

object instanceof Constructor

Examples

An instance of a class and of its parent:

class Animal {}
class Dog extends Animal {}
 
const rex = new Dog();
 
console.log(rex instanceof Dog);
console.log(rex instanceof Animal);
console.log(rex instanceof Array);

Output:

true
true
false

Different kinds of errors in catch:

try {
  JSON.parse('{');
} catch (error) {
  if (error instanceof SyntaxError) console.log('Bad JSON');
  else throw error;
}

Output:

Bad JSON

Notes

The operator does not work with primitives: 'text' instanceof String is false. Use typeof for them.

See also

  • typeof — Returns a string with the type of a value.
  • class — Declares a class — a template for objects with shared methods.
  • extends — Creates a subclass that inherits the parent's properties and methods.
  • Object.getPrototypeOf — Returns the prototype of an object.

Related recipes

In the tutorial

  • Inheritance — Class inheritance in JavaScript — extends, super, overriding methods and instanceof.

Thanks for reading!

Donate to the site — we work hard for you.