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.

<script>
	function calculateVolume(length) {
		return function (breadth) {
			return function (height) {
				return length * breadth * height;
			}
		}
	}
	console.log(calculateVolume(4)(5)(6));
</script>

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


Recommended Posts

View All

4 Ways of Passive Income for a Programmer


Everyone wants to make extra money, but owing to time limits and jobs, we can't devote more time to it.. Find out how to become a programmer who makes...

Difference between Function, Method and Constructor calls in JavaScript


You are probably used to thinking about functions, methods, and class constructors as three distinct things if you are experienced with object-oriente...

Learn JavaScript Closures with Code Examples


Master JavaScript closures with code examples! Our comprehensive guide explains how closures work and how to use them in your code. Start learning now...

The Difference Between Slice and Splice in JavaScript


Discover the nuances between slice() and splice() in JavaScript. Learn how to use these methods to manipulate arrays with ease. Read on to find out mo...

What is JSON? Know how it Works with Examples


Learn what JSON is and how it works with examples in this comprehensive guide. Discover the basics of JSON syntax, its applications, and why it has be...