In JavaScript, there are several approaches to checking whether an object is an array or not.
1. Using Array.isArray() Method (Recommended)
The most reliable and modern way to check if an object is an array in JavaScript is by using the Array.isArray()
method. This method was introduced in ECMAScript 5 (ES5) and is widely supported across modern browsers and environments.
const arr = [10, 20, 30, 40, 50]; const obj = { name: 'John' }; console.log(Array.isArray(arr)); // true console.log(Array.isArray(obj)); // false
2. Using instanceof Operator
The instanceof
operator is another common way to check if an object is an array. It checks if the prototype property of a constructor appears in the prototype chain of an object.
const arr = [10, 20, 30, 40, 50]; const obj = { name: 'John' }; console.log(arr instanceof Array); // true console.log(obj instanceof Array); // false
Limitations of instanceof
It can fail in some edge cases, especially if you are working with arrays across multiple windows or iframes. This is because each window/iframe has its own global Array
constructor, and the instanceof
operator checks for the prototype chain of the constructor from the current window’s context.
3. Using Object toString() Method
Before Array.isArray()
was available, developers often used Object toString()
to check if an object is an array. This method is still reliable and can be used as a fallback.
The toString()
method returns a string representation of the object in the format [object Type]
. For arrays, this will return [object Array]
.
const arr = [10, 20, 30, 40, 50]; const obj = { name: 'John' }; console.log(Object.prototype.toString.call(arr)); // [object Array] console.log(Object.prototype.toString.call(obj)); // [object Object]
Explanation
- This method is less error-prone than
instanceof
because it checks the internal object tag instead of relying on prototypes. - It’s supported in all JavaScript environments, even older ones.
4. Using constructor Property
Each JavaScript object has a constructor
property that points to the function that created the object. For arrays, the constructor is Array
.
const arr = [10, 20, 30, 40, 50]; const obj = { name: 'John' }; console.log(arr.constructor === Array); // true console.log(obj.constructor === Array); // false