There are several methods to check if a variable is an array or not. In this article, we will explore all methods with code examples and explanations.
1. Using Array.isArray() Method
The basic method to check if a variable is an array or not is by using the Array.isArray()
method. It is a built-in JavaScript method used to check the variable is an array or not.
let arr = [10, 20, 30, 40, 50]; let num = 42; console.log(Array.isArray(arr)); // Output: true console.log(Array.isArray(num)); // Output: false
2. Using instanceof Array
The instanceof
operator is used to check whether a variable is an instance of a specific constructor or not (in this case, it will be Array
).
let arr = [10, 20, 30, 40, 50]; let obj = {}; console.log(arr instanceof Array); // Output: true console.log(obj instanceof Array); // Output: false
3. Checking the Constructor Property
You can also check the constructor
property of a variable to check the given variable is an Array
or not.
let arr = [10, 20, 30, 40, 50]; let obj = {}; console.log(arr.constructor === Array); // Output: true console.log(obj.constructor === Array); // Output: false