How do I check if an object is an array in JavaScript without using Array.isArray()?
Alex K
alex k profile pic

To check if an object is an array in JavaScript without usingArray.isArray(), you can use theObject.prototype.toString.call() method. Here's an example:

1
2
3
4
5
6
7
8

function isArray(obj) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}

// Example usage
console.log(isArray([1, 2, 3])); // Output: true
console.log(isArray({ key: 'value' })); // Output: false

In the above code, theisArray() function takes an object as an argument. It usesObject.prototype.toString.call(obj) to retrieve the internal[[Class]] property of the object, which is a string representation of its type. For an array, the[[Class]] property will be"[object Array]". By comparing the result ofObject.prototype.toString.call(obj) with"[object Array]", we can determine if the object is an array or not. If the comparison returnstrue, then the object is an array. Otherwise, it is not. Note that this method works for most cases, but it may not be reliable if you're dealing with arrays that originate from different frames or contexts (e.g., iframes) due to differences in their[[Class]] values. In such cases, usingArray.isArray() is recommended for accurate results.