Skip to main content

Currying in JavaScript

Miscellaneous: Currying


What is currying in JavaScript?

View Answer:
Interview Response: Currying is an advanced procedure for working with functions. It is used not only in JavaScript but in other languages as well. Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c). Currying does not call a function; it just transforms it. Currying allows us to extract partials quickly.

Code Example:

function curry(f) {
// curry(f) does the currying transform
return function (a) {
return function (b) {
return f(a, b);
};
};
}

// usage
function sum(a, b) {
return a + b;
}

let curriedSum = curry(sum);

alert(curriedSum(1)(2)); // 3

What is the main rule of currying functions in JavaScript?

View Answer:
Interview Response: Currying necessitates that a function takes a fixed number of arguments. A function with rest parameters, such as f(...args), cannot be curried in this manner.

Code Example: This is an example of Advanced Currying.

function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args);
} else {
return function (...args2) {
return curried.apply(this, args.concat(args2));
};
}
};
}

function sum(a, b, c) {
return a + b + c;
}

let curriedSum = curry(sum);

alert(curriedSum(1, 2, 3)); // 6, still callable normally
alert(curriedSum(1)(2, 3)); // 6, currying of 1st arg
alert(curriedSum(1)(2)(3)); // 6, full currying