Search code examples
javascriptreturntostring

JS, return function name


I've just started to learn javascript and come across one task that I don't understand. Can anyone explain me why do we return function name "return f" in this example and what for do we use "f.toString"?

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

Solution

  • Lets start with a simplified version:

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

    It willwork much like yours, you can do:

    sum(1)(2)(3);//f
    sum(1)(2);//f
    

    However, they always return a function, so were not able to access the currentSum. Its in sums scope and as its never returned or passed, its impossible to get it. So we probably need another function we can call to get the current sum:

     function sum(currentSum) {
       function f(b) {
         currentSum += b;
         return f;
       }
    
      f.getSum = function() {
         return currentSum;
      };
    
      return f;
    }
    

    So now f has a property (functions are objects too), which is a function called getSum to get our variable

    sum(1)(2)(3)//f
    sum(1)(2)(3).getSum()//6 <= wohhooo
    

    But why do we call it toString ?

    When adding a variable to a string, its converted to a string, e.g.

    1+"one"//"1one"
    

    the same applies to objects/functions, but in this case, the js parser tries to call their toString method first, so:

    sum(1)(2)+"three"
    

    equals

    sum(1)(2).toString()+"three"
    

    the same conversion happens when passing non strings to alert.