How to use instanceof operator In Javascript
The instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object. This can be used to evaluate if the given variable has a prototype of ‘Array’.
Syntax:
variable instanceof Array
Return value: The operator returns a true boolean value if the variable is the same as what is specified (here an Array) and a false if it is not. This is shown in the example below.
Example: In this example, we will check if a given variable is an array or not using the instanceof operator in JavaScript.
function checkArray() {
let str = 'This is a string';
let num = 25;
let arr = [10, 20, 30, 40];
let ans = str instanceof Array;
console.log("Output for String:" + ans);
ans = num instanceof Array;
console.log("Output for Number:" + ans);
ans = arr instanceof Array;
console.log("Output for Array:" + ans);
}
checkArray();
Output
Output for String:false Output for Number:false Output for Array:true
How to check if a variable is an array in JavaScript?
This article will show you how to check whether the given variable value is an array or not.
Table of Content
- Using JavaScript isArray() method
- Using JavaScript instanceof operator
- Checking the constructor property of the variable
- Using Object.prototype.toString.call()
- Checking the Length Property
- Using Array.prototype.isPrototypeOf()