-1

I just learnt the arrays for-of loop which iterates through each elements of an array and I used it to empty an array using pop() which removes the last element of an array but this isn't working.

let skills = ["HTML", "CSS", "Javascript", "SASS", "Bootstrap", "Tailwind"];
for (let skill of skills) {
  skills.pop();
}
console.log(skills); // HTML , CSS, Javascript
Phil
  • 157,677
  • 23
  • 242
  • 245
Saad Ali
  • 59
  • 8
  • I admit that there are may other ways to remove all elements of an array but just testing out the logic. – Saad Ali Jul 11 '22 at 23:55
  • 2
    Consider that `for..of` iterates forwards but `pop()` removes elements from the end – Phil Jul 11 '22 at 23:56

1 Answers1

0

The array iterator is like a live collection; if the array changes while being iterated over, the next item(s) returned by the iterator will reflect the change. As you can see in the link above, it works by incrementing an index that starts from 0 until the length of the array has been reached.

for (let skill of skills) {

is, in this situation, nearly equivalent to

for (let i = 0; i < skills.length; i++) {
  const skill = skills[i]

The array iterator doesn't return a static amount of items determined when the iterator is initially called; the next item to be returned is determined on the fly on each iteration. So if you .pop an item from the array inside an iteration, there will be one fewer iteration overall than if you hadn't popped, unless you're already at the end of the array.

If there are 6 items in the array - as there are here - then you'll pop 3 times, and there will be 3 fewer iterations than the number of items - resulting in a total of 3 iterations total, and 3 items removed.

If you turned the array into one that didn't change while iterating over it, .pop would work. (This isn't a recommendation - there are better ways to empty an array - just for illustration, to make what's going on clearer.)

let skills = ["HTML", "CSS", "Javascript", "SASS", "Bootstrap", "Tailwind"];
for (let skill of [...skills]) {
  skills.pop();
}
console.log(skills); // empty

This works because [...skills] creates a separate array whose elements don't get removed when skills.pop is called.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320