How can I check if an object is an array?

 

You can check if an object is an array in JavaScript by using the Array.isArray() method or by checking the constructor property of the object. Here are examples of both methods:

  1. Using Array.isArray():
javascript
const myArray = [1, 2, 3]; const myObject = { key: 'value' }; if (Array.isArray(myArray)) { console.log('myArray is an array.'); } else { console.log('myArray is not an array.'); } if (Array.isArray(myObject)) { console.log('myObject is an array.'); } else { console.log('myObject is not an array.'); }

Output:

c
myArray is an array. myObject is not an array.
  1. Using the constructor property:
javascript
const myArray = [1, 2, 3]; const myObject = { key: 'value' }; if (myArray.constructor === Array) { console.log('myArray is an array.'); } else { console.log('myArray is not an array.'); } if (myObject.constructor === Array) { console.log('myObject is an array.'); } else { console.log('myObject is not an array.'); }

Output:

c
myArray is an array. myObject is not an array.

Both of these methods will allow you to determine if an object is an array in JavaScript. However, using Array.isArray() is generally considered a more reliable and recommended way to check for arrays because it also works with arrays created in different frames or iframes, which might have a different Array constructor.

Comments