Currently, I am following a JavaScript tutorial that covers the call
and apply
methods. One thing that has me puzzled is the behavior of an 'array-like object' used in one of the examples:
var arrayLikeObj = {
0: 'Marty',
1: 78,
2: 42,
3: ['Tim', 'Eric', 'Phil'],
length: 4
};
From what I understand, the length property in this object is not related to the Array.prototype.length
method; rather, it was manually set to give the object array-like properties.
However, after using the pop
method on the array-like object like this:
console.log(Array.prototype.pop.call(arrayLikeObj));
...the length property decreases!
console.log(arrayLikeObj) // Object {0: "Marty", 1: 78, 2: 42, length: 3}
This outcome raises questions. Could Array.prototype.length
be somehow overriding the existing length property in the object, transforming it into a length method?
To add to my confusion, when I create a new object without the predefined length
property and apply the same pop
operation:
var arrayLikeObj = {
0: 'Marty',
1: 78,
2: 42,
3: ['Tim', 'Eric', 'Phil']
};
console.log(Array.prototype.pop.call(arrayLikeObj));
console.log(arrayLikeObj);
The resulting object ends up with a length of 0:
{0: "Marty", 1: 78, 2: 42, 3: Array[3], length: 0}
This situation truly intrigues me, and I am eager to comprehend what exactly is going on here.