0

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?

JohnK
  • 6,865
  • 8
  • 49
  • 75
  • Here, we see closure, in one of its natural habitats. Currying functions essentially chain closures together, after the outer function has ran the inner function still has access to the `sum` variable via closure. – UncaughtTypeError May 26 '20 at 05:30
  • @UncaughtTypeError, thanks for your reponse! It would seem that the "should evaluate to these" functions are also the results of closures with currying. The question is why the inner function still has access to the `sum` variable after it should have been evaluated. – JohnK May 26 '20 at 15:08
  • 1
    If I'm understanding your question correctly, this would still be due to closure. The value of `sum` is till defined in the lexical scope of the outer function, allowing the inner function access to it even after the outer function has initialised and returned, and since this `sum` behaves as a sort of "global" variable within the containing lexical environment it can be updated on every iteration and it's value is "remembered" via closure. Does that make more sense? A closure is essentially a function that remembers its outer variables. – UncaughtTypeError May 26 '20 at 15:51

0 Answers0