I'm working through a tutorial on JavaScript's call
and apply
methods, and am confused by the behavior of an 'array-like object' used in the example:
var arrayLikeObj = {
0: 'Marty',
1: 78,
2: 42,
3: ['Tim', 'Eric', 'Phil'],
length: 4
};
My understanding is that the length property here is wholly unrelated to the Array.prototype.length
method, and was hard-coded in order to give the object it's necessary array-like properties.
However, when I pop
the array-like object as such:
console.log(Array.prototype.pop.call(arrayLikeObj));
...it's length property has decreased!
console.log(arrayLikeObj) // Object {0: "Marty", 1: 78, 2: 42, length: 3}
How is this possible!?
Does Array.prototype.length
somehow overwrite the existing length property in the object, turning it into a length method?
To further my confusion, when I declare an object without the hard-coded length
property and call the same pop
method:
var arrayLikeObj = {
0: 'Marty',
1: 78,
2: 42,
3: ['Tim', 'Eric', 'Phil']
};
console.log(Array.prototype.pop.call(arrayLikeObj));
console.log(arrayLikeObj);
The returned object has been assigned a length of 0:
{0: "Marty", 1: 78, 2: 42, 3: Array[3], length: 0}
I am very interested in understanding what is happening here.