What Is the Instanceof Operator in JavaScript?

About the Author:

Kellye Whitney
Our staff is always looking for the latest news, technologies and trends in the developer training space.
,

What Is the Instanceof Operator in JavaScript?

The instanceof is an important operator the checks a pre-existing and defined value then returns true if the object is its specified object type, or false if it isn’t. A basic example can be best shown through the following:

 
var colorTrue = new String(“black”);
colorTrue instanceof String; // returns true

var colorFalse = “green”; // object is not specified 
colorFalse instanceof String; // returns false, it is not a string.

The instanceof operator is self explanatory at this point. The second variable is not defined as a string, once the instanceof is called, it outputs a return false. Conversely, the first one is defined as a string and will return true in an output.

Instanceof in Action

There are a few more ways to display this operator. Something that is important to note is that instanceof will evaluate true if an object inherits a class’s prototype. In the succeeding example, we’ll define three different objects and apply the operator to each.

valueOne = 5;
valueTwo = 5.00;
value = “Custom” ; 

These three variables are an integer, float and a custom defined data type. Something to take note of in JavaScript is that variables don’t automatically define what a variable is. The programmer has to define a data type. Once these have been defined, then you use instanceof to check if each object is the specified type.

var value = new Custom();
value instanceof Custom; //returns true, as value is a Custom defined data type. 
value instanceof String; //returns false, as value is not a string, but a Custom defined data type. 

The operator of instanceof is simple while in use and can help users differentiate between what types of objects they’re dealing with while programming. The console will print out the distinction and you’ll be better off using the operator.