0

This is a piece of code that I couldn't reason about. These prototype array methods are used on elems object but I can't understand why length is affected by it. There is no array that has been defined whatsoever. Yet each add operation (via gather method) increments the 'length'. How does this object behave like an array ? Where are all these values stored in ? Can someone please shed some light on this ?

const elems = {
  length: 0,

  add: function(elem) {
    Array.prototype.push.call(this, elem);
  },
  gather: function(id) {
    this.add(document.getElementById(id))
  },
  find: function(callback) {
    return Array.prototype.find.call(this, callback);
  },
}

elems.gather('first');
console.log(elems.length === 1);

elems.gather('second');
console.log(elems.length === 2);

const found = elems.find((elem) => elem.id === 'second');
console.log(found.id === 'second');
<h1 id='first'>Hello</h1>
<h1 id='second'>Stack!</h1>

2
  • 1
    length property is changed because this is passed to the .call() method. Commented Jul 19, 2021 at 5:27
  • 1
    "Where are all these values stored in ?" - they are stored on the elem object where key is the index and value is the html string; try logging the elem object. Commented Jul 19, 2021 at 5:35

1 Answer 1

2

Because the native .push method explicitly takes the length of the array-like object that it's called on, adds one to it, and assigns that result to the new .length property:

1. Let O be ? ToObject(this value).
2. Let len be ? LengthOfArrayLike(O).
3. Let argCount be the number of elements in items.
4. If len + argCount > 253 - 1, throw a TypeError exception.
5. For each element E of items, do
a. Perform ? Set(O, ! ToString(𝔽(len)), E, true).
b. Set len to len + 1.
6. Perform ? Set(O, "length", 𝔽(len), true).

Where are all these values stored in ?

On the length property of the object. It's not a hidden internal slot.

Sign up to request clarification or add additional context in comments.

1 Comment

"On the length property of the object" - I think OP meant to ask where the values passed to the gather function, i.e. 'first' and 'second' are stored?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.