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 instanceof Array
true
> a2 instanceof Array
true
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 a2
looks 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]