js instanceof
The instanceof
operator in JavaScript is used to determine whether an object is an instance of a particular class. It can be used to check whether an object is an instance of a certain type, like a string, a number, an array, etc.
The syntax of the instanceof
operator is object instanceof constructor
. The object is the instance to be checked and the constructor is the class that the object being checked is an instance of. If the object is an instance of the constructor, then the instanceof
operator returns true
. Otherwise, it returns false
.
The instanceof
operator is useful for determining the type of an object, for example, when working with an array or a string. For example, if you want to check if an array is an instance of an Array, you can use the instanceof
operator like this:
var myArray = [1, 2, 3];
if (myArray instanceof Array) {
// do something
}
In the above example, the myArray
is an instance of the Array
constructor and so the instanceof
operator will return true
.
The instanceof
operator is also useful when dealing with objects. For example, if you have an object and you want to check if it is an instance of a particular class, you can use the instanceof
operator like this:
var myObject = {};
if (myObject instanceof Object) {
// do something
}
In the above example, the myObject
is an instance of the Object
constructor and so the instanceof
operator will return true
.
The instanceof
operator can also be used to determine whether a value is an instance of a certain type, such as a string, a number, etc. For example, if you want to check if a value is a number, you can use the instanceof
operator like this:
var myValue = 10;
if (myValue instanceof Number) {
// do something
}
In the above example, the myValue
is an instance of the Number
constructor and so the instanceof
operator will return true
.