Web Development with sumit

New JavaScript and Web Development content every day. Follow to join.

Member-only story

Everything about Currying in JavaScript

Sumit kumar Singh
Web Development with sumit
4 min readMay 9, 2023

--

Currying is a technique used in functional programming that allows you to transform a function with multiple arguments into a sequence of functions, each taking only one argument at a time. This concept is named after the mathematician Haskell Curry, who introduced it in the 1930s. In JavaScript, currying is a powerful tool that can improve code reusability, composability, and maintainability. In this article, we will explore currying in-depth, providing a comprehensive explanation and examples.

To understand currying, let’s start with a basic example. Consider a function called add that takes two arguments and returns their sum:

function add(x, y) {
return x + y;
}

console.log(add(3, 4)); // Output: 7

The add function takes two arguments, x and y, and returns their sum. Now, let's curry this function. We can use a technique called partial application to achieve currying:

function add(x) {
return function(y) {
return x + y;
};
}

console.log(add(3)(4)); // Output: 7

In the curried version, the add function now takes one argument, x, and returns another function that takes the second argument, y, and performs the addition. This allows us to call add(3) and obtain a new function that can be called with the remaining argument 4.

Currying provides several benefits. One advantage is that it allows us to create specialized functions from a more generic one. We can create a reusable addOne function by partially applying the add function:

const addOne = add(1);
console.log(addOne(5)); // Output: 6
console.log(addOne(10)); // Output: 11

Here, addOne is a new function derived from add that always adds 1 to its argument. We can reuse this function throughout our codebase without duplicating the logic.

Another advantage of currying is the ability to create higher-order functions that enhance composability. Consider a function called multiply that takes three arguments and returns their product:

function multiply(x, y, z) {
return x * y * z;
}

console.log(multiply(2, 3, 4)); // Output: 24

Now, let’s curry the multiply function:

function multiply(x) {
return function(y) {…

--

--

Web Development with sumit
Web Development with sumit

Published in Web Development with sumit

New JavaScript and Web Development content every day. Follow to join.

Sumit kumar Singh
Sumit kumar Singh

Written by Sumit kumar Singh

YouTube: https://shorturl.at/8zZ4B Topmate: https://topmate.io/sumit_kr_singh 📚 HTML, Angular, React, and JavaScript 🧑‍💻 Tips & tricks

Responses (1)