freeCodeCamp Challenge Guide: Accumulator factory

Accumulator factory


Solution 1 (Click to Show/Hide)
function accumulator(sum) {
    return (n) => sum += n;

Explanation: A function, and the block/environment surrounding that function constitute a closure.

Variables defined in the outer function of a closure are retained in memory even after the execution of the inner function completes. A local variable in reference to an outer function acts like a global variable for an inner function defined within the outer function.

Closures - JavaScript | MDN (

Here, the function accumulator(sum) and the inner function being returned make up a Closure. The variable sum retains its value after the inner function is executed. The inner function adds the passed argument to the sum variable and returns the value of sum after the change.

1 Like