I'm learning JavaScript. I wrote this code to learn the map function. But then I got confused as to why is this not mapping over it continuously as with each map sequence a new element is pushed to the array. Shouldn't it continue to push new elements as it is mapping over ? Why does the map function only run for the original three elements and not for the new pushed ones?
I tried to debug it in the node environment and the arr
variable goes in a closure. I know what a closure but I'm not able to understand what is going on here.
let array = [1, 2, 3];
array.map((element) => {
array.push(10);
console.log(element);
});
I expect that the output should be 1,2,3,10,10,10,10,10,10,10,10......10
But the actual output is only 1,2,3
.
.map()
is specified to behave – Lessliearr
, which isn't defined; I assumed you meantarray
. – LesslieThe range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback.
– Anyfor
loop – Anaximenes