Sobes.tech
Junior

How to check if an object is an array?

sobes.tech AI

Answer from AI

There are several ways:

  1. Use Array.isArray(). This is the most reliable and recommended method.

    const arr = [1, 2, 3];
    const obj = { a: 1 };
    
    console.log(Array.isArray(arr)); // true
    console.log(Array.isArray(obj)); // false
    
  2. Use instanceof Array. Works for arrays created in the current frame or window. May give false results when working with frames or cross-domain scenarios.

    const arr = [1, 2, 3];
    const obj = { a: 1 };
    
    console.log(arr instanceof Array); // true
    console.log(obj instanceof Array); // false
    
  3. Use Object.prototype.toString.call(). Returns a string representation of the object type. For arrays, it is "[object Array]".

    const arr = [1, 2, 3];
    const obj = { a: 1 };
    
    console.log(Object.prototype.toString.call(arr) === '[object Array]'); // true
    console.log(Object.prototype.toString.call(obj) === '[object Array]'); // false
    

The most preferred method is using Array.isArray(), as it is reliable and has no side effects related to the execution context.