Member-only story

JavaScript Interview and Prep: Currying

Marika Lam
2 min readJun 20, 2024

--

What is Currying

  • Currying is a technique in functional programming that allows you to transform a function that takes multiple arguments into a sequence of functions that each take one argument.
  • Here is a simple JavaScript method (no curry)
function add (a, b) {
return a + b;
}

add(3, 4); // returns 7
  • Now let’s curry this function
function add (a) {
return function (b) {
return a + b;
}
}
  • This is a function that takes one argument, a, and returns a function that takes another argument, b, and that function returns their sum.
add(3)(4); // returns 7

var add3 = add(3); // returns a function

add3(4); // returns 7
  • The first statement returns 7, like the add(3, 4) statement.
  • The second statement defines a new function called add3 that will add 3 to its argument. This is what some may call a closure.
  • The third statement uses the add3 operation to add 3 to 4, again producing 7 as a result.

Example prompt

  • Please implement a curry() function, which accepts a function and return a curried one.

Solution

--

--

No responses yet