Function currying in JavaScript means that if a function takes multiple arguments instead of passing all arguments at a the same time, takes the first one and returns a new function, which takes the second one and returns a new function, which takes the third one, etc. until all arguments are completed.
Currying will make your code easier to refactor. Currying also creates a more declarative code base
Example :
Without Currying
function sum(a,b,c){
return a+b+c
}
console.log(sum(1,3,5))
Output: 9
With Currying
Method 1:
let sum=function(a){
return function(b){
return function(c)
{
return a+b+c;
}
}
}
console.log(sum(1)(3)(5))
Output: 9
If number of arguments are large
Method 1:
const sum = function (a) {
return function (b) {
if (b) {
return sum(a+b);
}
return a;
}
};
console.log(sum(1)(3)(5)())
Output : 9
Method 2:
const sum=a=>b=>b?sum(a+b):a;
console.log(sum(1)(2)(3)())
Output : 9
Until it get an empty argument function will be called.
Are you new to React.js or Just started learning and struggling with react.js project? We have team of react.js developer to help you in react.js project, assignment and for learning react.js at affordable price.
Comments