Member-only story
How to Check if a Variable is an Array in JavaScript
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 array");
}
3. Checking the constructor type
The constructor type of a variable is the type of object that was used to create the variable. In this case, the constructor type of an array is the Array
constructor.
Here is an example of how to check the constructor type of a variable to see if it is an array:
var myArray = [1, 2, 3];
var constructorType = myArray.constructor;
if (constructorType === Array) {
console.log("myArray is an array");
} else {
console.log("myArray is not an array");
}
I hope this blog post has been helpful. Thanks for reading!