Skip to content
Advertisement

Javascript toString trick in adding function. How does it work?

Can somebody explain to me how the toString trick works in the following example. The function adds all the arguments being passed for each call so add(1)(2)(3); equals 6.

jsFiddle

function add(a) {
  var sum = a;
    return function self(a) {
      sum += a;
      self.toString = function () {
          return sum;
      }
      return self;
  }
}

console.log(add(1)(2)(3));

Advertisement

Answer

Since the function is a chain function, you need to return a function to be chained which then returns itself.

However, you also need a meaningful way to get its result.

In jQuery, for example, you might see .get() used to extract results from a chained operation. This is much the same, using .toString() to mean “if you’re putting me somewhere a string is expected, return the result”.

Advertisement