Currying in JavaScript

Currying in JavaScript

Published
October 28, 2022
 
 

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 }
/* 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
 
 
/*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
 
 

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)....()
 
 

How can we manipulate DOM using currying?

 
<div> <h1 id="header">Hello World</h1> </div>
 
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;
 
2️⃣ Now call the function with element id and and the content
 
const updateHeaderText = updateElemText('header'); updateHeaderText('Hello Currying!');
 
What is showing up on the browser? 👀
 
Hope this blog helped you understand currying better.