1 2 3 4
const obj = [1, 2, 3]; const isArray = Array.isArray(obj);
Array.isArray() method returns
true if the provided object is an array; otherwise, it returns
false. 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;
instanceof operator checks if an object is an instance of a specific class. In this case, we check if
obj is an instance of the
Array 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]";
Object.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 the
typeof 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. The
Array.isArray() method is generally recommended as it provides a more reliable and straightforward way to determine if an object is an array.