Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this JavaScript map NOT an Infinite Loop?

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.

like image 464
ExpertNoob Avatar asked Jun 11 '19 14:06

ExpertNoob


People also ask

Is map better than for loop JavaScript?

map() works way faster than for loop.

How is map different from for loop in JavaScript?

map does exactly the same thing as what the for loop does, except that map creates a new array with the result of calling a provided function on every element in the calling array.

What is an infinite loop in JavaScript?

An infinite loop is a piece of code that keeps running forever as the terminating condition is never reached. An infinite loop can crash your program or browser and freeze your computer. To avoid such incidents it is important to be aware of infinite loops so that we can avoid them.

Is map function a loop?

map() function is “looping” over each item in the array and assigning the item (i.e. person in the second and third examples) and the current index (i.e. i in the first and third examples) as parameters to the function that we define.


1 Answers

To quote from MDN:

The 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. If existing elements of the array are changed, their value as passed to callback will be the value at the time map visits them.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description

So, it behaves like that because that is how it is designed. And it is designed that way, amongst other reasons, to prevent infinite loops!

map is a function from the Functional Programming world, where immutability is an important principle. According to this principle, if you call map on an input (and other variables don't change) you will always get exactly the same result. Allowing modification of the input breaks immutability.

like image 81
Joe Avatar answered Sep 28 '22 04:09

Joe