Whether a JavaScript object is an array?

Typically, an array is created with the following code:

let arr = [1, 2, 3];

or using Array function:

let arr = Array(1, 2, 3);

The prototype of the created arrays is Array.prototype. Hence, the expression arr instanceof Array return true.

However, we can create Array-like objects, and make them behave like a real array. For example:

let arr = {0: 10, 1: 12, 2: 14, length: 3};

Currently arr is still a plain object. We can make it become this of a function defined on Array.prototype, for example:

Array.prototype.push.call(arr, 16);

Then the content of arr will become:

{0: 10, 1: 12, 2: 14, length: 3};

We can also forcefully set the prototype of arr to Array.prototype:

Object.setPrototypeOf(arr, Array.prototype);

Then any function on Array.prototype can be invoked as a arr, like push above. And arr instanceof Array returns true.

However, Array.isArray(arr) still returns false, and Object.prototype.toString.call(arr) still returns “[object Object]” rather than “[object Array]".

The two function calls determine whether arr is an actual array by checking whether it is created via Array constructor. This is not changeable after the array is created.

The package is-array uses the following way to determine whether arr is an array:

  1. if Array.isArray is available, use Array.isArray(arr);
  2. Otherwise, use Object.prototype.toString.call(arr) === '[object Array]'

Comments

Leave a comment