Javascript Function Executed In This Pattern "xyz()()" Throws Error?
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.
Solution 1:
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.
functioncurrySum(x) {
returnfunction(y) {
returnfunction(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:
functionsum() {
var s = 0;
for (let n ofarguments) {
s += n;
}
return s;
}
// summing multiple argumentsconsole.log(sum(1, 2, 3, 4));
// summing all numbers in an arrayconsole.log(sum.apply(null, [1, 2, 3, 4]));
Post a Comment for "Javascript Function Executed In This Pattern "xyz()()" Throws Error?"