The instanceof operator in JavaScript

In JavaScript, the instanceof operator lets you check if an object is an instance of a particular type of object (no shit, Sherlock).

More specifically, the MDN Web Docs state:

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.

Let’s look at a simple example.

 * Represents a Pokemon
 * @constructor
 * @param {String} name  The name of the Pokemon
 * @param {String} color The color of the Pokemon
 * @param {String} type  The type of the Pokemon
function Pokemon (name, color, type) { = name;
  this.color = color;
  this.type = type;

// Create a new Pokemon object
var pikachu = new Pokemon("Pikachu", "Yellow", "Electric");

console.log(pikachu instanceof Pokemon); // true

In the code above:

  1. We have a constructor function that lets us create Pokemon objects.
  2. We create a Pokemon object and save it to the pikachu variable.
  3. Logging pikachu instanceof Pokemon shows true in the console.

The console shows true because the pikachu variable holds an object that is an instance of the Pokemon constructor.

In my next post, I’ll show you a recent use case I found for the instanceof operator. In the meantime, you can learn more on the MDN Web Docs.

If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!