In this answer I don't understand what's going on with the immediately invoked function that provides a running or cumulative sum of the elements of the entered array. The first version is from linked answer and the second version is equivalent:
const cumulativeSum = (sum => value => sum += value)(0);
console.log([5, 10, 3, 2].map(cumulativeSum));
const cumulativeSum2 = (function(sum){ return function(value) {return sum += value}})(0)
console.log([5, 10, 3, 2].map(cumulativeSum2));
It would seem that the immediate invocations should evaluate to these:
cumulativeSum = value => 0 += value
cumulativeSum2 = function(value) {return 0 += value}
But the console indicates that these are actually
cumulativeSum = value => sum += value;
cumulativeSum2 = function(value) {return sum += value;}
How does the sum
variable survive the immediately invocation? What is going on with these functions? Is there a name for it?