Example of using closures in javascript

Example of using closures in javascript
0.0 0


Can someone explain how this works? I found a few explanations, but I still don’t understand why there is “return f;” line on the last line of function sum.

function sum(a) {

  var currentSum = a;

  function f(b) {
    currentSum += b;
    return f;

  f.toString = function() {
    return currentSum;

  return f;

alert( sum(1)(2) ); // 3
alert( sum(5)(-1)(2) ); // 6
alert( sum(6)(-1)(-2)(-3) ); // 0
alert( sum(0)(1)(2)(3)(4)(5) ); // 15

Thank you!


That code doesn’t work for me so I don’t understand it. If you figure it out, let me know!

Ah ok sorry. If you instead of alerting do console log, you need to add .toString() to get the total out.

The return f; is returning the function I believe. The function you declared earlier.