JavaScript Currying
Javascript
1 September 2022
Currying simply means evaluating functions with multiple arguments and decomposing them into a sequence of functions with a single argument.
It is a technique in functional programming, transformation of the function of multiple arguments into several functions of a single argument in sequence.
Example...
Normal function
function sum(a, b, c) {
return a + b + c;
}
let evaluateSum = sum(1,2,3);
Curried function
function sum(a) {
return function(b) {
return function(c) {
return a + b + c;
}
}
}
let evaluateSum = sum(1)(2)(3);
Q1. Convert normal function into curring function?
function curry (func) {
return function curriedFun(...args) {
if(args.length >= func.length) {
return func(...args);
}
else {
return function(...next) {
return curriedFun(...args, ...next);
}
}
}
}
const sum = (a, b, c) => a + b + c;
const totalSum = curry(sum);
console.log(totalSum(1)(2)(3));
Q2. Curring function that takes any number of arguments?
function add(a) {
return function(b) {
if(b) return add(a + b);
return a;
}
}
console.log(add(10)(20)(10)(10)());
One important use is to manipulate the HTML DOM.
function changeHeaderContent(id) {
return function(content) {
document.getElementById(id).textContent = content;
}
}
const changeHeader = changeHeaderContent('heading'); // id of html tag
changeHeader('Hello Roshan'); // value to change
Summary
Currying is a transform that makes f(a,b,c) callable as f(a)(b)(c).
Currying is a transform that makes f(a,b,c) callable as f(a)(b)(c).
Comments
Leave a Comment
Your email address will not be published.
Categories
You May Also Like
Javascript
Clock
30 March 2026
HTML & CSS
Responsive lightbox
4 February 2025
Javascript
Display pdf as image
10 July 2025
Javascript
Custom Calendar
10 July 2025
Javascript
Circular Progress Bar
16 August 2024
HTML & CSS
Adaptive Navbar
10 July 2025
Javascript
JavaScript Currying
9 March 2024
Javascript
Google reCAPTCHA
10 July 2025
Javascript
Braintree
10 July 2025
jQuery
Image Slider
10 July 2025