DEV Community

loading...

Verifying an Object's Constructor with instanceof

Randy Rivera
Once I truly put my mind on something, I won't ever stop.
Updated on ・1 min read
  • Continued
  • Anytime a constructor function creates a new object, that object is said to be an instance of its constructor. JavaScript gives a convenient way to verify this with the instanceof operator. instanceof allows you to compare an object to a constructor, returning true or false based on whether or not that object was created with the constructor.

  • Here's an example:

function Dog(name, color) {
  this.name = name;
  this.color = color;
  this.numLegs = 4;
}

let goldenRetriever = new Dog("Naruto", orange);

goldenRetriever instanceof Dog; // will display true
Enter fullscreen mode Exit fullscreen mode
  • This instanceof method would return true.
  • If an object is created without using a constructor, instanceof will verify that it is not an instance of that constructor:

Discussion (1)

Some comments have been hidden by the post's author - find out more