In order to distinguish whether variable is an array or not we have couple of options.
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
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
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!