DEV Community

Randy Rivera
Randy Rivera

Posted on • Edited on

Verifying an Object's Constructor with instanceof

  • 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:

Top comments (1)

Collapse
 
simonas88 profile image
Info Comment hidden by post author - thread only accessible via permalink
simonas88

Shouldn't goldenRetriever instanceof House; return false?

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