JS Interview #9 — JavaScript Currying

Mighty Ghost Hack
Mighty ghost hack
Published in
2 min readApr 8, 2023
JavaScript Currying

In this article, we are going to discuss currying in JavaScript. Here, we will see how currying works and how it will be helpful for software developers.

What is currying?

Currying is a function that accepts multiple arguments. It will transform this function into a series of functions, where every little function will accept one

It is a transformation of functions that translates a function from callable as sum(1, 2, 3) into callable as sum(1)(2)(3).

Here function with three arguments so instead of taking all arguments once, it takes the first one, returns a new function that takes the second one, and returns a new function that takes the third one, and it will keep going until all arguments are fulfilled.

Let’s Understand By Single Examples

First, I’m going to create a simple function that accepts two parameters

const sum = (a, b) => {
return a+b
}
console.log(sum(1, 1)) // 2

What happened here is that this function is adding all the parameters of the numbers which we have passed.

Now, this first example is just a simple function that accepts multiple parameters.

Let’s Converting an existing function into a curried function

In this example, this function is going to accept one argument and return a series of functions

const sumCurry = a => {
return b => {
return a+b;
}
}

console.log(sumCurry(1)(1)) // 2

how we implemented the same function but with a curried version that takes one argument a and returns a function that takes another argument b, and that function returns their sum, which gave us the same output as an example one: 5.

Also if you wish to increase the number of arguments then curried version program would be below

const sumCurry = a => {
return b => {
return c => {
return a+b+c;
};
}
}

console.log(sumCurry(1)(1)(1)) // 3

Key Points to remember

  • It divides your function into multiple smaller functions that can handle one responsibility. This makes your function pure and less prone to errors and side effects
  • It is used in functional programming to create a higher-order function.
  • it makes code readable.

To understand in a much better way here is the video link

--

--

Mighty Ghost Hack
Mighty ghost hack

A passionate full-stack developer, Ethical Hacker, Blogger, Youtuber and many more