What does instanceof do?
The instanceof operator returns TRUE or FALSE depending on whether a given value or variable is of a certain type or class – it checks whether a value is an instance of a given object class or type.
The purpose of instanceof may seem confusing – you already have typeof, so what do you need instanceof for?
typeof will simply return a string containing the name of the type or class of the variable. In contrast, instanceof will return a boolean value confirming whether a given variable matches a given class at a programmatic level.
What is a Type/Class?
A variable type determines what kind of data it can store and what can be done for it. A variable type is defined by its class – which is the code that defines what data can be stored and the functions and associated behavior.
For example, string typed variables are sequences of characters that can be joined and split (think words and sentences), while numeric typed variables contain numeric values which can be used in arithmetic.
The syntax for using instanceof is as follows:
OBJECT instanceof CONSTRUCTOR
- OBJECT is the variable or value you want to check
- CONSTRUCTOR is the name of the class you want to check whether OBJECT is an instance of
- A boolean TRUE or FALSE value will be returned
- instanceof checks the entire prototype chain of the OBJECT
- This means that instanceof can return a positive result for two different CONSTRUCTORs if one constructor is derived from the other
This example creates a Person class, and then an object is created using this class. instanceof is then used to confirm that the created object is of the Person class.