The instanceof keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language.
- What is it?
- What problems does it solve?
- When is it appropriate and when not?
instanceof
The Left Hand Side (LHS) operand is the actual object being tested to the Right Hand Side (RHS) operand which is the actual constructor of a class. The basic definition is:
Here are some good examples and here is an example taken directly from Mozilla’s developer site:
One thing worth mentioning is
instanceofevaluates to true if the object inherits from the class’s prototype:That is
p instanceof Personis true sincepinherits fromPerson.prototype.Per the OP’s request
I’ve added a small example with some sample code and an explanation.
When you declare a variable you give it a specific type.
For instance:
The above show you some variables, namely
i,f, andc. The types areinteger,floatand a user definedCustomerdata type. Types such as the above could be for any language, not just JavaScript. However, with JavaScript when you declare a variable you don’t explicitly define a type,var x, x could be a number / string / a user defined data type. So whatinstanceofdoes is it checks the object to see if it is of the type specified so from above taking theCustomerobject we could do:Above we’ve seen that
cwas declared with the typeCustomer. We’ve new’d it and checked whether it is of typeCustomeror not. Sure is, it returns true. Then still using theCustomerobject we check if it is aString. Nope, definitely not aStringwe newed aCustomerobject not aStringobject. In this case, it returns false.It really is that simple!