An array iterator functions like a dynamic collection; as the array is modified during iteration, the items returned by the iterator will reflect these changes. By incrementing an index from 0 to the array's length, the iterator navigates through the elements seamlessly.
for (let skill of skills) {
In this context, the previous code snippet is almost identical to
for (let i = 0; i < skills.length; i++) {
const skill = skills[i]
The array iterator does not return a fixed set of items upon initialization; rather, each item returned is determined dynamically during iteration. Therefore, if you remove an item using .pop
within the loop, there will be fewer iterations compared to when no removal occurs, except when already at the end of the array.
For instance, with 6 items in the array - as present here - and popping 3 times would result in only 3 iterations remaining out of the original 6, along with 3 items removed.
If the array remained unchanged while being iterated, the .pop
method would function normally. However, it's worth noting that there are more efficient ways to clear an array than this approach.
let skills = ["HTML", "CSS", "Javascript", "SASS", "Bootstrap", "Tailwind"];
for (let skill of [...skills]) {
skills.pop();
}
console.log(skills); // empty
The trick lies in using [...skills]
to create a separate array where elements remain intact even after calling skills.pop
.