0

Just started doing some JS stuff and can't get my head around something. I have the following task:

Write a function that adds a number passed to it to an internal sum and returns itself with its internal sum set to the new value, so it can be chained in a functional manner. Input: Your function needs to take one numeric argument. Output: Your function needs to return itself with an updated context.

I came up with the following code after some hints from here and there:

function add(num) {
  let sum = num;

  function func(num2) {
    sum += num2;
    
    return func;
  }

  func.toString = function() {return sum;};
  return func;
}

console.log(
  add(1)
);
console.log(
  add(1)(6)(-3)
);  

What exactly do func.toString = function() {return sum;} and return func do? Before that I get it - closure and returning a function and etc.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
Simomir
  • 21
  • 6
  • Which last two lines? The last two of `add`, or the last two of the example `add(1) ...`? – evolutionxbox May 24 '21 at 09:50
  • func.toString = function() {return sum;}; return func; – Simomir May 24 '21 at 09:51
  • 1
    If you comment out the line and run the same examples again, you can see exactly why it was there - the result of `add(1)` and `add(1)(6)(-3)` is `func`, so without changing its `toString` method you don't see the resulting value. – jonrsharpe May 24 '21 at 09:51
  • @jonrsharpe So basically I rewrite the toString method of the function so I can see the resulting sum. – Simomir May 24 '21 at 10:05
  • https://stackoverflow.com/a/18067040/1048572 – Bergi May 24 '21 at 12:48

0 Answers0