JavaScript·100 questions

QUESTION: What is currying?

Answer

Currying in JavaScript is the process of transforming a function with multiple arguments, taking the form f(a, b, c), into a chain of functions, each of which takes exactly one argument. The result is a construction of the form f(a)(b)(c).

This powerful approach is actively used in functional programming to create more flexible and reusable code. In addition, it is indispensable for implementing partial application of arguments, when some parameters are fixed in advance and the remaining ones are passed later.

A classic example in modern syntax is the arrow function const add = a => b => a + b. In this case, calling add(

will return a new function that waits for the next argument b, and calling add(5)(
will return the final result of the addition.

This approach allows creating specialized functions based on universal templates. For example, a logging function can be curried so that it first accepts the message severity level and then the text itself, which simplifies passing ready-made loggers to various application modules.

Furthermore, currying opens up wide possibilities for function composition, where the output data of one operation is smoothly passed to the input of another. This makes the code declarative, clean, easy to test, and readable within large enterprise projects.

Was this answer helpful?

More questions in this topic

Related questions from other topics