What is Currying
Transforming a function that takes multiple parameters into a series of functions that take a single parameter
For example, there is a function to make a sandwich, which builds a sandwich by passing three parameters:
Currying this function means breaking it down into three functions, each accepting a single parameter:
This way of writing is still somewhat hard to read, so we can further simplify it using arrow functions:
This is currying. Now that you understand this cool pattern, what are the benefits of passing functions one by one instead of passing parameters?
Benefits of Currying
Higher Reusability
Using the sandwich example again, if not all parameters are fully passed, for instance, if only bread
and meat
are passed, it will return a function indicating that the vegetable
parameter needs to be provided:
This creates a partially applied function that can be used to build different sandwiches without passing all parameters each time. You must have already noticed that this awesome feature can be immediately applied in actual development, such as opening a sandwich shop to produce different types of sandwiches: