-2
 var recursiveSum = function() {
    console.log(arguments.length);
 }
 recursiveSum(1)(2)(3);

Why is it throwing not a function error? I am using NodeJs to execute above sript.

Nitish
  • 409
  • 8
  • 17
  • `recursiveSum` should return a function. – Tushar Jul 13 '17 at 05:17
  • `although it a valid syntax?` because it isn't valid syntax – Jaromanda X Jul 13 '17 at 05:19
  • 1
    Well not all valid syntax does work. `undefined(2)` is valid syntax either (which actually is just what you're doing, considering the return value of `recursiveSum(1)`) – Bergi Jul 13 '17 at 05:19
  • 1
    Have a look at https://stackoverflow.com/questions/5832891/javascript-sum-function, https://stackoverflow.com/questions/28927510/add-function-that-works-with-different-combinations-of-chaining-arguments, https://stackoverflow.com/questions/25578728/puzzle-js-function-that-returns-itself-until-there-are-no-arguments, https://stackoverflow.com/a/18067040/1048572 to see how this is done correctly – Bergi Jul 13 '17 at 05:20

1 Answers1

2

It would only work if recursiveSum would return a function.

Right now, you try to execute the return value of recursiveSum(1) as a function. It isn't (it's undefined), and thus an error is thrown; you try to execute undefined(2)(3).

You could do something like this.

function currySum(x) {
  return function(y) {
    return function(z) {
      return x + y + z;
    }
  }
}

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

If you have a variable number of arguments and want to use this currying syntax, look at any of the questions Bergi mentioned in a comment: this one, that one, another one or here.


Alternatively, write an actual variadic function:

function sum() {
  var s = 0;
  for (let n of arguments) {
    s += n;
  }
  return s;
}

// summing multiple arguments
console.log(sum(1, 2, 3, 4));
// summing all numbers in an array
console.log(sum.apply(null, [1, 2, 3, 4]));
Just a student
  • 10,560
  • 2
  • 41
  • 69