| by Arround The Web | No comments

What is the instanceof Operator in JavaScript?

While declaring a variable in JavaScript, we do not explicitly define its type. In contrast to other languages, we just use “var x”, which might be a number, array, string, or a user-defined datatype. For example, in C or C++, the programmer specifies the data type when declaring a variable, such as an int, float, and so on. However, JavaScript can benefit from having an “instanceof” operator to determine whether an object belongs to a specific type.

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:

objectName instanceof objectType

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”:

var languages = ['JavaScript', 'Java', 'Python', 'C', 'C++'];

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:

var type = languages instanceof String;

Print the resultant value on the console:

console.log("The type of the declared object is String? " + type);

It can be seen that the “languages” is not string type object because the instanceOf operator returned “false”:

Check it with object type “Array”:

var type = languages instanceof 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.

Share Button

Source: linuxhint.com

Leave a Reply