Junior — Middle
Can you explain the concept of currying in JavaScript and how it is used?
sobes.tech AI
Answer from AI
Currying is a technique in functional programming where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument.
In JavaScript, this allows creating more flexible and reusable functions by partially applying arguments.
Example of currying:
function multiply(a) {
return function(b) {
return a * b;
};
}
const double = multiply(2);
console.log(double(5)); // 10
Here, multiply takes one argument a and returns a function that takes b. This enables creating specialized functions, for example, double multiplies any number by 2.
Currying is useful for partial application of functions and creating chains of calls.