Currying in JavaScript: A Flavorful Guide
Currying is a powerful technique in JavaScript that can make your code more readable and reusable. It is the process of transforming a function with multiple arguments into a sequence of functions each with a single argument.
Basic Currying
Here's a simple example of a curried function:
function multiply(a) {
return function (b) {
return a * b
}
}
const multiplyByTwo = multiply(2)
console.log(multiplyByTwo(3)) // Outputs: 6
In the above example, multiply
is a curried function. When we call multiply(2)
, it returns a new function that will multiply its input by 2.
Practical Use of Currying
Currying can be very useful in practice. For example, you can use it to create reusable functions with some arguments "preset". Here's an example:
function greeter(greeting) {
return function (name) {
return `${greeting}, ${name}!`
}
}
const sayHello = greeter('Hello')
console.log(sayHello('Alex')) // Outputs: "Hello, Alex!"
In this example, greeter
is a curried function that creates customized greeting functions.
Understanding currying can help you write more efficient and reusable JavaScript code.