Currying in JavaScript

What is currying?

Currying is a technique of evaluating a function with multiple arguments, into a sequence of functions with a single argument.

OR

In other words, while a function, rather than taking all arguments at one time, takes the primary one and goes back to a new function that takes the second and returns a new function which takes the third one, and so forth, till all arguments have been fulfilled.

Why is it useful?

  1. a) It helps to avoid passing the same variable again and again.
  2. b) It is extremely useful in event handling.
  3. c) Code can be configured and reused with ease

Syntax:

Example1

In the following example ,considering the fact that currying is used,parameters have been passed one by one(volume(11)(2)(3))  till the remaining function is referred to as the last parameter.

console.log(volume(11)(2)(3));

Example2

console.log(curriedAddTwo(1)(2)) // evaluates to 3

The function above works as followed:

  • curriedAddTwo() is declared, accepting a single parameter a;
  • when called, curriedAddTwo() is provided the argument 1, returning a new nameless function that accepts a single parameter b;
  • The returned function (step 2) is called straight away with argument 2, returning the expected value 1+2.

By definition, a curried function is one that takes many parameters and returns a function with a fixed arity of 1. Although that can sound confusing, it actually means that a curried function will constantly go back to a function that takes exactly 1 argument. As a result of this, we have to pass in arguments in individual parenthesis blocks, or our function will now no longer work.

How does currying work?

Currying works by natural closure. The closure is created by the nested functions to maintain access to each of the arguments. So inner functions have access to all arguments.

Leave a Reply