PCA PCA - 3 years ago 122
Javascript Question

Closure in Javascript with multiple brackets

Could any one explain how this function alert, when more no of brackets of parameters are passed. I could not able to understand it clearly.

function sum(a) {

var sum = a

function f(b) {
sum += b
return f
}

f.toString = function() { return sum }

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

Answer Source

The first time your function is called, the first value is stored in sum. After that function f(b) will be returned, maintaining the provisional result in sum. With each consecutive call you execute function f - you perform sum += b and return f again. If a string context is required (such as in the alert, or a console.log) f.toString is called instead, returning the result (sum).

function sum(a) {

  var sum = a

  function f(b) {
    sum += b
    return f  //<- from second call, f is returned each time
              //   so you can chain those calls indefinitely
              //   function sum basically got "overridden" by f
  }

  f.toString = function() { return sum }

  return f //<- after first call, f is returned
}

Explanation:

alert( sum(6)(-1)(-2)(-3) )  // 0
           /\ function sum called, f returned
              /\ the returned function f is called, f returns itself
                  /\ again
                     /\ and again
                         /\ at last, alert() requires string context,
                            so f.toString is getting invoked now instead of f
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download