Skip to content Skip to sidebar Skip to footer

Array.isarray() Returns False For Array Created With Object.create()

I am facing a strange problem in Javascript. It may be due to lack of understanding from my side. I have an array a1: var a1 = [1, 2, 3] Then I add a new element to this array a1

Solution 1:

From the MDN documentation:

The Object.create() method creates a new object with the specified prototype object and properties.

When you call Object.create(a1)you're not creating a real array, you are creating an object which looks like an array, but it's not. In fact, you could even try this:

> a1 instanceofArraytrue
> a2 instanceofArraytrue

and see that the result is true for both the variables.

Then what does Array.isArray() do? Well, it doesn't obviously use the isinstanceof statement. To be sure the variable is a real array, it checks using the Object.prototype.toString() method, like this:

> Object.prototype.toString.call(a1)
"[object Array]"
> Object.prototype.toString.call(a2)
"[object Object]"
> Object.prototype.toString.call(a1) === "[object Array]"true
> Object.prototype.toString.call(a2) === "[object Array]"false

This is why calling Array.isArray() gives you these results: because it performs the above check. Now you are sure that, even if a2looks like an array, it is not an array at all.


Also, to clarify: when you do a1['newEntry'] = 4 you're not adding a new element to the array. You are instead creating the property newEntry with value 4 on your existing array. To add an element to an array, you should use the push() method, like this:

> a1 = [1, 2, 3]> a1.push(4)> console.log(a1)
[1, 2, 3, 4]

Solution 2:

Object.create() is creating an Object rather than an Array, thus when checking against Array.isArray(), it will return false.

Consider instead Array.slice(), e.g.

var a2 = a1.slice(0);

Source: Clone Arrays with JavaScript

Post a Comment for "Array.isarray() Returns False For Array Created With Object.create()"