JavaScript·100 questions

QUESTION: What is instanceof?

Answer

The instanceof operator in JavaScript is used to check whether a specific object is part of the prototype chain of a certain class or constructor function. The usage syntax is extremely simple and looks like obj instanceof Class. If, during the search through the prototype chain of the obj object, a prototype matching the prototype property of the checked Class is found, the operator returns true; otherwise, it returns false.

This mechanism works equally well with both modern classes and traditional constructor functions. However, it should be remembered that instanceof is not intended for checking primitive data types such as strings, numbers, or boolean values. For primitives, the typeof operator is traditionally used.

The JavaScript language also provides the ability to customize the behavior of the instanceof operator using the special built-in Symbol.hasInstance symbol. By defining this static method inside your class, you can completely override the check logic, making it custom. This allows developers to create flexible libraries and frameworks where checking whether objects belong to data types can be managed programmatically.

Was this answer helpful?

More questions in this topic

Related questions from other topics