About me

I am a full stack .net developer with 5 years of experience in front-end and back-end technologies like HTML, CSS, Jquery, Angular, Typescript, Bootstrap, C#, MSSQL and Mongodb. I have done bachelor's in computer engineering from Gujarat Technological University. I have worked on web applications, Web APIs, Windows Forms, Web Forms, Tray applications and corporate websites. Programming is my hobby and I have starting writing blog to provide a platform for those who want to grow their career as a fullstack .NET developers.

Click here to know more about me

Currying in JavaScript

Currying Functions in JS

You may find different definitions for currying across the internet but when you simplify all those definitions, it is all about making a function callable from f(a,b,..,n) to f(a)(b)...(n)

Use Case: Whenever we have knowledge of some of the parameter values of a function, but to complete the operation we need rest of the parameter values which are not there while initializing the function

Suppose, we are making a game and we need to display a specific message regarding a team that will always have 3 members in 3 languages (English, Spanish, and German). 

What will you do? Will you create 3 different functions for different languages or is there something which we can do within a single function? How you will associate different people's names who have joined that team with the statement?

This can be achieved through currying. Let's see how we can do that.

We can create a function, DisplayMessage as shown below:

function DisplayMessage (message) {

         return function (member_1) {

                return function (member_2) {

                    return function (member_3) {

                          return  message + " " + member_1 + ", " + member_2 + ", and " + member_3;

                    }

              }

       }

}

This can be invoked as shown below:

var EnglishMsg = DisplayMessage("Welcome to the team")

EnglishMsg("Albert")("Isaac")("Stephan")

Output for this will be as shown below:

JSFiddle code and output
JSFiddle code and output

For other languages we can do it as shown below:

Output of the Example
The output of the Example

This way, different messages can be associated with the team member's names. Here is the JSFiddle link.

We can chain any number of parameters within the functions as per the requirement.

I hope, you understood what currying is. For any queries, you can write to me at info@beawesomewithprogramming.co.in. To get notified for the releases, subscribe through email. If you found this article useful, please share it. Thank you 😊.