Let consider a simple use of map()
function in JavaScript:
[1,2].map(x => x + 1).map(x => x + 2); // [3,4]
I am wondering whether each of arrow function calls is executed in separate loops or if the functions are applied to array elements in one loop. I know that for example in java those function would be executed in one loop (using Streams from Java 8). In that case we can chain some functions that are non-terminal (they return Stream on which we can call another function) but those operations are not executed until we use a terminal function (like collect()
that transforms Stream into some collection, like an array). Thus, all the operations (maps, filters etc.) are merged so that all of them can run in one loop.
On the other hand we have a JavaScript where we know that Array.prototype.map()
returns another array, so it seems like each map()
call is executed in separate loop. But that would be quite a waste of execution time! The simplest answer is that it's all optimized by engine so the functions are indeed executed in one loop, but I couldn't find any information that this is the case.
A side question - can we say that Java's Stream
is a functor? It seems like it is - it has a map function that transforms collection to same-size collection and returns a stream. But on the other hand, as mentioned before, this map function does not in fact modify anything until we call some terminal function.