javascript-300x120

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:

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.

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.

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.

Comments