In JavaScript, arrays are a special type of object, which means using basic methods like typeof
doesn’t give accurate results for distinguishing arrays from other objects. To correctly identify whether a variable is an array, JavaScript provides several approaches, each suited for different use cases.
This article will walk you through all the reliable methods to check if a variable is an array in JavaScript, including modern techniques and some legacy approaches.
1. Using Array.isArray() Method
The most reliable and straightforward way to check if a variable is an array is by using the Array.isArray()
method. It is a built-in JavaScript method specifically designed for this purpose.
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 checks whether a variable is an instance of a specific constructor, in this case, 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 see if it matches Array
.
let arr = [10, 20, 30, 40, 50]; let obj = {}; console.log(arr.constructor === Array); // Output: true console.log(obj.constructor === Array); // Output: false