Trusted answers to developer questions

What is currying in JavaScript?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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.

let some_func = (input_1, input_2, input_3) => {
return input_1 + input_2 + input_3
}
let output = some_func(1,2,3) //All arguments passed at once and return value saved in "output" variable
console.log(output)

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)

RELATED TAGS

javascript
currying
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?