In JavaScript, you can check if a variable is an array using several methods. Here are four commonly used approaches:
Array.isArray():
The Array.isArray() method is the recommended and most reliable way to check if a variable is an array. It returns true if the provided value is an array; otherwise, it returns false.
Example:
const arr = [1, 2, 3];
const notArr = ‘Not an array’;
console.log(Array.isArray(arr)); // Output: true
console.log(Array.isArray(notArr)); // Output: false
Instanceof operator:
The instanceof operator can also be used to check if a variable is an instance of the Array object. However, it has some limitations. It only works if the variable and the array are from the same global context, and it can be unreliable if you’re dealing with multiple frames or if the variable has been passed between different contexts.
Example:
const arr = [1, 2, 3];
const notArr = ‘Not an array’;
console.log(arr instanceof Array); // Output: true
console.log(notArr instanceof Array); // Output: false
Object.prototype.toString.call():
Another approach is to use the Object.prototype.toString.call() method. It returns a string representation of the provided value’s internal [[Class]] property. For an array, it returns “[object Array]”. This method is more verbose but can be useful in older environments that don’t support Array.isArray().
Example:
const arr = [1, 2, 3];
const notArr = ‘Not an array’;
console.log(Object.prototype.toString.call(arr) === ‘[object Array]’); // Output: true
console.log(Object.prototype.toString.call(notArr) === ‘[object Array]’); // Output: false
Array.prototype.isArray() polyfill:
If you’re working in an environment that doesn’t have native support for Array.isArray(), you can use a polyfill to add the method to the Array prototype. This approach ensures consistent behavior across different environments.
Example:
if (!Array.isArray) {
Array.isArray = function (value) {
return Object.prototype.toString.call(value) === ‘[object Array]’;
};
}
const arr = [1, 2, 3];
const notArr = ‘Not an array’;
console.log(Array.isArray(arr)); // Output: true
console.log(Array.isArray(notArr)); // Output: false
By using one of these methods, you can reliably check whether a variable is an array in JavaScript. The Array.isArray() method is the recommended approach as it provides the most straightforward and reliable solution.
