75.8k views
1 vote
What is the instanceof operator in JavaScript?

A. It is used for mathematical operations involving instances of objects.
B. It checks if two objects are equal in value and type.
C. It tests if an object is an instance of a particular constructor or class.
D. It is used to compare two strings in JavaScript.

1 Answer

1 vote

Final answer:

Option C: The instanceof operator in JavaScript is used to check if an object is an instance of a particular constructor or class, by comparing the object's prototype chain against the constructor's prototype.

Step-by-step explanation:

The instanceof operator in JavaScript is used for type-checking in object-oriented programming languages. Specifically, option C is correct: it tests if an object is an instance of a particular constructor or class. This means that the instanceof operator compares the prototype chain of an object against a specified constructor's prototype property to determine if the object inherits from that constructor.

For example, consider the following code where Vehicle is a constructor function or a class.

function Vehicle() {}
let car = new Vehicle();
console.log(car instanceof Vehicle); // returns true

In this example, car instanceof Vehicle returns true because car was created by the Vehicle constructor, and hence it is an instance of Vehicle.

User Biodiscus
by
8.4k points