DEV Community

Dragoljub Bogićević
Dragoljub Bogićević

Posted on


How to Recognize an Array

In order to distinguish whether variable is an array or not we have couple of options.

But before we start it is good to mention that arrays in JavaScript are special kind of objects as you can see down bellow:

let testArray = [1, 2, 3];

console.log(typeof testArray); // object

We can check if variable is an array with this code snippet:

let testArray = [1, 2, 3];

console.log(Array.isArray(testArray)); // true

The problem with this solution is that Array.isArray() method is introduced in ECMAScript 5, so if you need support for older browsers you can do something like this by using constructor property:

let testArray = [1, 2, 3];

console.log(testArray.constructor === Array);  // true
console.log( === 'Array');  // true
console.log(testArray.constructor.toString().indexOf('Array') > -1); // true

Also, we are allowed to use instanceof operator:

let testArray = [1, 2, 3];

console.log(testArray instanceof Array); // true


Although, we can create an array by using new Array() we should prefer way we used in examples above for simplicity, readability and execution speed.

Thank you for reading!

Top comments (2)

patarapolw profile image
Pacharapol Withayasakpunt • Edited

There are two more,

testArray.constructor === Array  // true === 'Array'  // true

Also, I believe .constructor.toString() === 'function Array() { [native code] }'

But if a class extends Array, most cases become false, except Array.isArray and instanceof.

bogicevic7 profile image
Dragoljub Bogićević

Thank you for the response, I have included your suggestions...