Currying is the process of splitting up a function with several parameters into several functions, each with just one argument. Currying is named for Haskell Curry, a mathematician. A n-ary function can become a unary function by currying.

Let's look at an example of an n-ary function and how a currying function is created.

const multiArgFunction = (a, b, c) => a + b + c;
console.log(multiArgFunction(1, 2, 3)); // 6

const curryUnaryFunction = (a) => (b) => (c) => a + b + c;
curryUnaryFunction(1); // returns a function: b => c =>  1 + b + c
curryUnaryFunction(1)(2); // returns a function: c => 3 + c
curryUnaryFunction(1)(2)(3); // returns the number 6

Using closures, this example demonstrates the currying approach. The calculateVolume() function will be used during the execution thread. There is an anonymous function within that takes a parameter and outputs some code. It will be built because we are exposing our function from another function. The lexical environment of the parent and the function definition are always present in the closure and are kept together as a bundle. Therefore, regardless of where we call them, all inner functions will always have access to the parent variable.

The next argument is ready to be given as soon as the returned result has been received as a function; this procedure will continue until the second-to-last function.

The innermost return keyword finally produces the anticipated outcome.

	function calculateVolume(length) {
		return function (breadth) {
			return function (height) {
				return length * breadth * height;

Curried functions are excellent for enhancing functional composition and code reuse.

Recommended Posts

View All

Difference Between == and === in JavaScript

Learn the Difference Between == and === in JavaScript. Discover how each operator compares values and data types, and when to use them in code.

Calculate the length of an associative array using JavaScript

Associative arrays are regular arrays in JavaScript where an element is present at a specific index.

What is memoization?

Memoization is a programming technique that improves efficiency by caching results of expensive function calls. Learn more about it here.

What is the let keyword in JavaScript?

Learn all about the let keyword in JavaScript and how it differs from var. Explore its scope, hoisting, and best practices for usage.

JavaScript Program to Create Objects in Different Ways

Learn different ways to create objects using JavaScript with our step-by-step guide. From object literals to constructor functions and classes, this p...