Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

What is currying and how does it work?

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a series of functions that each take a single argument. This allows for partial application of functions. For example, a function f(a, b, c) can be curried into f(a)(b)(c). Here's a simple example in JavaScript:

function add(a) {
return function (b) {
return function (c) {
return a + b + c;
};
};
}
const addOne = add(1);
const addOneAndTwo = addOne(2);
const result = addOneAndTwo(3); // result is 6

What is currying and how does it work?

Definition

Currying is a functional programming technique where a function with multiple arguments is decomposed into a sequence of functions, each taking a single argument. This allows for the partial application of functions, enabling more flexible and reusable code.

How it works

  1. Transformation: A function that takes multiple arguments is transformed into a series of nested functions, each taking one argument.
  2. Partial application: You can call the curried function with fewer arguments than it expects, and it will return a new function that takes the remaining arguments.

Example in JavaScript

Here's a simple example to illustrate currying in JavaScript:

// Non-curried function
function add(a, b, c) {
return a + b + c;
}
// Curried version of the same function
function curriedAdd(a) {
return function (b) {
return function (c) {
return a + b + c;
};
};
}
// Using the curried function
const addOne = curriedAdd(1);
const addOneAndTwo = addOne(2);
const result = addOneAndTwo(3); // result is 6

Benefits of currying

  1. Reusability: Curried functions can be reused with different sets of arguments.
  2. Partial application: You can create new functions by fixing some arguments of the original function.
  3. Function composition: Currying makes it easier to compose functions, leading to more readable and maintainable code.

Practical example

Consider a function that calculates the volume of a rectangular prism:

function volume(length, width, height) {
return length * width * height;
}
// Curried version
function curriedVolume(length) {
return function (width) {
return function (height) {
return length * width * height;
};
};
}
// Using the curried function
const volumeWithLength5 = curriedVolume(5);
const volumeWithLength5AndWidth4 = volumeWithLength5(4);
const result = volumeWithLength5AndWidth4(3); // result is 60

Currying with arrow functions

You can also use arrow functions to make the syntax more concise:

const curriedAdd = (a) => (b) => (c) => a + b + c;
const addOne = curriedAdd(1);
const addOneAndTwo = addOne(2);
const result = addOneAndTwo(3); // result is 6

Further reading

Edit on GitHub