JavaScript Currying
Bharath Kumar Murugan
Full Stack Web Developer | ReactJS, Node.js, NextJS | AWS | Docker | Kubernetes | Python
JavaScript currying is a technique used to transform a function that takes multiple arguments into a sequence of functions that each take a single argument. The resulting functions can be called individually, or the entire sequence can be called as a single function, with each argument supplied one at a time.
To put it simply, currying is like breaking down a complex function into smaller, simpler functions that can be composed together.
Here's an example of a function that takes two arguments and returns their sum:
function add(a, b) {
return a + b;
}
To curry this function, we can use a higher-order function that returns a new function that expects one argument at a time:
function add(a) {
return function(b) {
return a + b;
};
}
This function can now be used like this:
领英推荐
const add2 = add(2); // returns a function that expects one argument
const result = add2(3); // returns 5
Here, we first create a new function add2 by passing the first argument "2" to the "add" function. This returns a new function that expects the second argument. We then call add2 with the second argument "3", which returns the result "5".
Currying can also be achieved using ES6 arrow functions:
const add = a => b => a + b;
const add2 = add(2);
const result = add2(3); // returns 5
Here, we use arrow functions to create the curried function add. The function add takes one argument "a" and returns another arrow function that takes one argument "b" and returns the sum of "a" and "b". We can then use this function in the same way as the previous example.
Currying can be a powerful technique when used appropriately. It can help to simplify complex functions, increase code re-usability, and enable easier function composition.
Hello Bharath... We post 100's of job opportunities for developers daily here. Candidates can talk to HRs directly. Feel free to share it with your network. Visit this link - https://jobs.hulkhire.com And start applying.. Will be happy to address your concerns, if any