Let’s dive into the fundamentals of the JavaScript instanceof
operator, which is used to determine if an object is an instance of a specific class or its ancestor in the prototype chain.
In the following example, we have an object called myCar
, which is an instance of the Fiesta
class. The instanceof
operator allows us to check if myCar
is an instance of Fiesta
or Car
(since Fiesta
extends Car
).
class Car {}
class Fiesta extends Car {}
const myCar = new Fiesta();
myCar instanceof Fiesta; // true
myCar instanceof Car; // true
By using the instanceof
operator, we obtain true
for both myCar instanceof Fiesta
and myCar instanceof Car
.
Using the instanceof
operator can be helpful in scenarios where you need to ensure that an object belongs to a specific class or has inherited properties and methods from a particular ancestor.
With a clear understanding of the JavaScript instanceof
operator, you can confidently utilize it to check object instances and their relationships in your JavaScript applications.