There's a handful of different ways to pass an "arbitrary" amount of arguments to a function. Perhaps the most useful for your case is the arguments
object. In the scope of every function is an array-like object that holds all of the arguments passed to the function.
function shout(msg) {
for (var i = 0; i < arguments.length; i++)
console.log(arguments[i]);
}
shout("This", "is", "JavaScript!"); // Logs all three strings, one line at a time
Despite it seeming like the function only accepts one argument, you can plug in as many as you'd like, and the function will cycle through all of them. Thus, converting this for your code:
function sum(a) {
var total = 0;
for (var i = 0; i < arguments.length; i++)
total = total + arguments[i];
return total;
}
sum(1, 2); // Returns 3
Two things to note:
- Because you're accessing the arguments object, you really don't "need" any sort of arguments list in the function definition (i.e. you don't need the
a
in sum(a)
), but it's generally considered a good idea to provide some indication of what the function expects.
- The arguments object is array-like, but is NOT a true array; don't go trying to use array functions on it such as push or pop unless you want to make a mess of things.
As for the specific sum(1)(2)
syntax however--if that is very specifically what you need--I'm stumped. In theory, to have an arbitrary chain like that, you'd need your function to return an object that is both a function and a number... which breaks fundamental rules of JavaScript. I don't think it's possible without some extremely clever (and likely extremely dangerous) editing of built in objects, which is generally frowned upon unless there is an extremely good reason for doing so.