Table of contents
1.
Introduction
2.
Definition of Currying
3.
Uses and Benefits of Currying
4.
Example of Currying
4.1.
Output
5.
Advanced Curry Implementation
6.
Frequently Asked Questions
6.1.
Who created the technique of currying?
6.2.
What are functions?
6.3.
 
6.4.
Demonstrate currying using ES6.
6.5.
What is lambda calculus?
7.
Conclusion
Last Updated: Mar 27, 2024

JS Currying

Author Pankhuri Goel
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Currying is a lambda calculus concept, but don't be put off by that; it's really simple to use.

Currying is a function that takes one argument at a time and returns a new function that is waiting for the next one. It's a function transformation that turns f(a, b, c) into f(a)(b)(c).

We'll look at what currying is in Javascript, why you should use it, and how to do it with various code demonstrations.

Also Read About, Javascript hasOwnProperty

Definition of Currying

Currying is the process of evaluating functions with numerous parameters and breaking them down into a series of single-argument functions.

Currying is when a function, rather than taking all arguments at once, take the first one and returns a new function, which then takes the second one and returns a new function, and so on until all arguments are completed. 

In other words, to get this form of translation, we just wrap a function inside a function, which means we'll return a function from another function. The parent function takes the first argument and returns the function that will take the next parameter, and so on until the number of arguments is exhausted. Hopefully, the function that receives the last parameter produces the desired outcome.

The translation of function happens as follows:

function basicFunction(arg1, arg2, arg3, …) => function curriedFunction(arg1)(arg2)(arg3)(... 

Uses and Benefits of Currying

The currying function is used in a variety of ways.

  • It makes it easier to avoid passing the same variable many times.
  • It comes in handy while dealing with events.

 

Currying is ideal for a number of reasons:

  • Currying is a process of double-checking that you have everything you need before moving forward.
  • It separates your function into several smaller functions, each of which can handle a single duty. This ensures that your function is error-free and free of side effects.
  • It saves you from having to pass the same variable over and over again.
  • It is used to generate a higher-order function in functional programming.

Example of Currying

Currying is a function that takes several arguments and returns the result. It will break this function down into a sequence of smaller functions, each of which will take one argument:

//Noncurried version
const add = (x, y, z) => {
    return x + y + z
}
console.log(add(6, 4, 10)) // Output-20

//Curried version
const addCurry = (x) => {
    return (y) => {
        return (z) => {
            return x + y + z
        }
    }
}
console.log(addCurry(6)(4)(10)) //Output-20

Output

Advanced Curry Implementation

Here's the "advanced" curry implementation for multi-argument functions that we might use above if you want to dive into the specifics.

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(x, y, z) {
  return x + y + z;
}

let curriedSum = curry(sum);

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

The wrapper curried, which looks like follows, is the result of calling curry(func).

// func is the function to be transformed
function curried(...args) {
  if (args.length >= func.length) { 
    return func.apply(this, args);
  } 
  else {
    return function(...args2) { 
      return curried.apply(this, args.concat(args2));
    }
  }
};

There are two execution branches when we run it:

  • If the number of arguments given is equal to or greater than the length of the original function's definition (func.length), simply use func.apply to send the call to it.
  • Otherwise, get a partial: we haven't yet called func. Instead, another wrapper is returned, which will re-apply curried with the new arguments as well as the prior ones.

If we call it again, we'll either get a new partial (if there aren't enough arguments) or the result. you can practice by yourself on a javascript compiler.

Frequently Asked Questions

Who created the technique of currying?

The technique of currying was created by an American mathematician named Haskell Curry.

 

What are functions?

Functions in JavaScript are used to conduct various types of operations. The JavaScript functions can be reused in the code several times.
Syntax: 

function functionName(argument1, argument2, argument3, …){
//statement block
  }

 

Demonstrate currying using ES6.

The modern technique of implementing currying using the ES6 arrow function is demonstrated as follows:

const sendRequest = greet => name => msg =>
`${greet} ${name}, ${msg}`
sendRequest('Hi')('Jane')('How are you?')

Output: Hi Jane, How are you?

 

What is lambda calculus?

The lambda calculus is a formal mathematical logic framework for expressing computations based on function abstraction and application utilising variable binding and substitution. It's a computational paradigm that can be used to simulate any Turing computer.

Conclusion

In this article, we learned about currying in JavaScript. We also learnt its uses, benefits and implementation. 

We hope this blog has helped you enhance your knowledge. If you want to learn more, check out our articles on Destructuring - Coding Ninjas Coding Ninjas StudioArrow functions in JavaScript - Coding Ninjas Coding Ninjas StudioMutation Observer in JavaScript - Coding Ninjas Coding Ninjas Studio and Function Expression - Coding Ninjas Coding Ninjas Studio. Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practice top problems, follow guided paths, attempt mock tests, read interview experiencesinterview bundle, solve problems, participate in contests and much more!

Happy Reading!

Live masterclass