How do I check if an object is an array in JavaScript?
Benjamin C
benjamin c profile pic

In JavaScript, you can check if an object is an array using various methods. Here are a few approaches to accomplish this: 1. Using Array.isArray():

1
2
3
4

   const obj = [1, 2, 3];
   const isArray = Array.isArray(obj);
   

TheArray.isArray() method returnstrue if the provided object is an array; otherwise, it returnsfalse. This method is widely supported in modern browsers and is the recommended approach. 2. Using instanceof Array:

1
2
3
4

   const obj = [1, 2, 3];
   const isArray = obj instanceof Array;
   

Theinstanceof operator checks if an object is an instance of a specific class. In this case, we check ifobj is an instance of theArray class. However, note that this approach can have limitations when working with arrays across different frames or contexts. 3. Using Object.prototype.toString():

1
2
3
4
5

   const obj = [1, 2, 3];
   const type = Object.prototype.toString.call(obj);
   const isArray = type === "[object Array]";
   

TheObject.prototype.toString() method returns a string representing the object's type. When called on an array, it returns"[object Array]". You can compare the result with"[object Array]" to determine if the object is an array. It's important to note that thetypeof operator is not suitable for checking if an object is an array since it returns"object" for arrays as well as other objects. Choose the method that best fits your needs based on compatibility requirements and your specific use case. TheArray.isArray() method is generally recommended as it provides a more reliable and straightforward way to determine if an object is an array.