How to Recognize an Array
Dragoljub Bogićević
Posted on February 22, 2020
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(testArray.constructor.name === '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
Note:
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!
Posted on February 22, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 23, 2024