Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 658
PCA Avatar asked Aug 15 '13 11:08

PCA


2 Answers

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
like image 161
Christoph Avatar answered Sep 17 '22 03:09

Christoph


The thing to look at is this piece of code

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

This function returns reference to itself so it can be called as many times as possible. An important thing about it is that it has a tostring function that gets called and since tostring is defined inside function sum() it has access to the variable sum and its value current value (that is changed by f() )

like image 20
U.P Avatar answered Sep 17 '22 03:09

U.P