What do we call this type of argument passing mul(1)(2)(3) how to solve this and how to solve such scenario in case of n arguments passed like this. I want to understand how this concept works.
Asked
Active
Viewed 3,128 times
2 Answers
6
It is called currying.
The main part is to return the same function again and again.
Then you need a mechanism to get the result. In Javascript, the toString
method is called if the calling function requires a primitive value.
function mul(x) {
function f(y) { // the function to return
x *= y; // update the value
return f; // return the function
};
f.toString = function () { // overwrite toString prototype
return x; // return value
};
return f; // return function, enable currying
}
console.log(mul(1)(2)(3));
console.log(mul(1)(2)(3)(4)(5)(6));

Nina Scholz
- 376,160
- 25
- 347
- 392
1
This is called "currying" and is a short hand form for the result of a function call being another function that immediately gets invoked with another parameter.
First:
mul(1)
Is called and would return a function. Then that function would be called with the second argument:
resultingFunctionFromCallingmul(2)
Finally, that call would return yet another function that would be called with the final argument:
resultingFunctionFromCallingtheFirstResultingFunction(3)
Here's an example:
function a(input){
console.log("function a called with " + input);
return b;
}
function b(input){
console.log("function b called with " + input);
return c;
}
function c(input){
console.log("function c called with " + input);
}
a("This is")(" a ")(" test.");

Scott Marcus
- 64,069
- 6
- 49
- 71