How to Check if a Variable is an Array in JavaScript
2 min readJul 24, 2023
In JavaScript, there are a few ways to check if a variable is an array. Here are three of the most common methods:
- Using the
Array.isArray()
method. - Using the
instanceof
operator. - Checking the constructor type.
1. Using the Array.isArray()
method
The Array.isArray()
method is a built-in method that takes a single argument, the variable you want to check. If the variable is an array, the method will return true
. Otherwise, it will return false
.
Example
var myArray = [1, 2, 3];
if (Array.isArray(myArray)) {
console.log("myArray is an array");
} else {
console.log("myArray is not an array");
}
2. Using the instanceof
operator
The instanceof
operator takes two arguments: the variable you want to check and the constructor you want to check it against. In this case, the constructor you want to check against is the Array
constructor.
Here is an example of how to use the instanceof
operator to check if a variable is an array:
var myArray = [1, 2, 3];
if (myArray instanceof Array) {
console.log("myArray is an array");
} else {
console.log("myArray is not an…