What is the instanceof Operator in JavaScript?
This article will describe the “instanceof” operator in JavaScript.
What is the “instanceof” Operator in JavaScript?
The “instanceof” operator is used for determining the object type in JavaScript. It provides a boolean result, values called “true” or “false”. If the object is an instance of the particular class, it gives “true”, else, it outputs “false”.
How to Use “instanceof” Operator in JavaScript?
Utilize the given syntax for the “instanceof” operator:
Here:
- “objectName” indicates the name of the object.
- “objectType” indicates the type of the object, such as Number, String, Array, Object, and so on.
Example: Using “instanceof” Operator in JavaScript
Create an array named “languages”:
As we know, everything in JavaScript is an object, so the array “languages” is an object. Check the type of the object, whether the specified variable is a “String” type or not:
Print the resultant value on the console:
It can be seen that the “languages” is not string type object because the instanceOf operator returned “false”:
Check it with object type “Array”:
The output displays “true” which indicates that “languages” is an array:
That’s all about the usage of the instanceof operator in JavaScript.
Conclusion
In JavaScript, we declare variables without specifying their data type, such as “var x”, which might be a number, array, string, or a user-defined datatype. While in other programming languages such as C, or C++, the programmer specifies the data type when declaring a variable, such as an int, float, and so on. So, the “instanceof” operator in JavaScript is utilized to determine/check the object type. If the object is an instance of the particular class, it gives “true”, else, it outputs “false”. This article discussed the JavaScript instanceof operator.
Source: linuxhint.com