The problem is that the JavaScript operator typeof returns “object”:
var numbers = [2, 3, 4];
typeof numbers;
//object
Why?
As we have already seen in this post, JavaScript Arrays: A Separate Data Type Or Objects?, JavaScript arrays are objects.
Method 1
We can use Array.isArray() method which was introduced in ECMAScript 5.
var numbers = [2, 3, 4];
Array.isArray(numbers);
// true
👎 This method is not supported in older browsers.
Method 2
We can make a our function and use constructor property to know whether it’s an array.
var numbers = [2, 3, 4];
function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
isArray(numbers);
// true
Let’s understand it.
The constructor property returns an array’s constructor function:
var numbers = [2, 3, 4];
console.log(numbers.constructor);
// [Function: Array]
which we convert to a string and get the index of word “Array”. If it’s the array then the word “array” will be there and will return positive value.
array constructor functions numbers objects operators