Did some notice how loop constructs forEach and for/of behave on "added during iteration" items? ForEach ignores the fact that there are newly added items in the array, and for/of alters iterator on the fly and keeps going until no elements are left in the array. What is the reason for this phenomenon, using smart words? 1-st post on the stackoverflow so no judge if explanation is simple.... Thanks
let my_array1 = [1,2,3]
let my_array2 = ["a", "b", "c"]
//extra iteration cycles were not dynamically added. Loop ends after pre-defined # of cycles.
my_array1.forEach((value, index, the_array) => {
if (value == 3){
// my_array1.push(3)
the_array.push(3) // works like so as well
}
})
console.log(`my_array1 after iteration ${my_array1}`)
//extra iteration cycles WERE dynamically added. Infinite loop!!!
for (let value of my_array2){
if (value == "c"){
my_array2.push("c")
}
}
console.log(`my_array2 after iteration ${my_array2}`)