What is currying in JavaScript?

In functional programming, currying is the process of converting a function, that takes multiple arguments at once, to a function that takes these arguments step by step.

How does it work?

A function F that takes in arguments A, B, C and returns a value R, when curried, can be broken down into three functions X, Y, Z.

Function X takes in A as an argument and returns a function Y, which in turn takes in B as an argument and returns a function Z, which takes in C as an argument and finally returns the required value R.

Standard function
Standard function
Curried function
Curried function

Code

1. Multiple arguments

Let’s see how a function taking in multiple arguments can be curried to take one argument at a time.

2. Single argument

However, note that the arguments do not need to be passed one by one. In the code below, one argument is passed at the first step and two arguments are passed at the second step.

let some_func = input_1 => (input_2, input_3) => {
return input_1 + input_2 + input_3
}
let output_1 = some_func(1)//First argument passed, the returned function is saved in variable "output_1"
console.log(output_1)
let output_2 = output_1(2, 3)//Second and third arguments passed, the returned value is saved in variable "output_2"
console.log(output_2)
Copyright ©2024 Educative, Inc. All rights reserved