- What is it?
- What problems does it solve?
- When is it appropriate and when not?
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:
Checks the current object and returns true if the object is of the specified object type.
var color1 = new String("green"); color1 instanceof String; // returns true var color2 = "coral"; //no type specified color2 instanceof String; // returns false (color2 is not a String object)
One thing worth mentioning is
instanceof evaluates to true if the object inherits from the classe’s prototype:
var p = new Person("Jon"); p instanceof Person
p instanceof Person is true since
p inherits from
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.
int i; float f; Customer c;
The above show you some variables, namely
c. The types are
float and a user defined
var x, x could be a number / string / a user defined data type. So what
instanceof does is it checks the object to see if it is of the type specified so from above taking the
Customer object we could do:
var c = new Customer(); c instanceof Customer; //Returns true as c is just a customer c instanceof String; //Returns false as c is not a string, it's a customer silly!
Above we’ve seen that
c was declared with the type
Customer. We’ve new’d it and checked whether it is of type
Customer or not. Sure is, it returns true. Then still using the
Customer object we check if it is a
String. Nope, definitely not a
String we newed a
Customer object not a
String object. In this case, it returns false.
It really is that simple!