DEV Community

Cover image for Currying in JavaScript
vedanth bora
vedanth bora

Posted on

Currying in JavaScript

What is Currying?

Currying is a function that takes one argument at a time and returns a new function expecting the next argument. It is a conversion of functions from callable as f(a,b,c) into callable as f(a)(b)(c).

Currying doesn’t call a function. It just transforms a function. They are constructed by chaining closures by immediately returning their inner functions simultaneously.

How does currying work?

Currying is a function that takes multiple arguments as input. It transform the function into a number of functions where every function will accept one argument.

Let’s understand this with examples

***Convert f(a, b) into f(a)(b)*

/* f(a,b) implementation */

function f(a,b) {
    return a + b
}
Enter fullscreen mode Exit fullscreen mode
/* f(a)(b) implementation */

function f(a) {
    return (b) {
          return a + b
        }
}

console.log(f(1)(2)) // 2
console.log(f(1)); /* () => {} */        // will retrun a function
Enter fullscreen mode Exit fullscreen mode
/*Simple function*/ 
const add = (a, b, c)=>{
    return a + b + c
}

console.log(add(1, 2 ,3)); // 6

/* Curried Function */

const addCurry = (a) => { // takes one argument
    return (b) => {                 //takes second argument
        return (c) => {             //takes third argument
            return a + b + c
        }
    }
}

console.log(addCurry(1)(2)(3)); //6
Enter fullscreen mode Exit fullscreen mode

A *currying function that takes infinite arguments.*

const sum = function(a) {
    return function(b) {
        if (b) {
            return sum(a + b);
        } else {
            return a;
        }
    }
}

// sum(1)(2)(3)....() 
Enter fullscreen mode Exit fullscreen mode

How can we manipulate DOM using currying?

<div>
  <h1 id="header">Hello World</h1>
</div>
Enter fullscreen mode Exit fullscreen mode

want browser to show "Hello Currying" instead of "Hello World".

Let's try it using currying.

Steps:

1️⃣ Take the id of the element as one argument and the content inside the element as another argument.

const updateElemText = (id) => (content) => document.querySelector(`#${id}`).textContent= content;
Enter fullscreen mode Exit fullscreen mode

2️⃣ Now call the function with element id and and the content

const updateHeaderText = updateElemText('header');

updateHeaderText('Hello Currying!');
Enter fullscreen mode Exit fullscreen mode

What is showing up on the browser? 👀

Hope this blog helped you understand currying better.

Top comments (0)