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 theprototype
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) {
this.name = 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:
- We have a constructor function that lets us create Pokemon objects.
- We create a Pokemon object and save it to the
pikachu
variable. - Logging
pikachu instanceof Pokemon
showstrue
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.