🟨 JavaScript Q17 / 121

What is currying?

AI-Powered Answer ✓ Answered

Currying is a functional programming technique where a function that takes multiple arguments is transformed into a sequence of functions, each taking a single argument.

What is Currying?

In essence, currying takes a function f(a, b, c) and transforms it into f(a)(b)(c). Instead of calling f with all its arguments at once, you call it with the first argument, which then returns a new function. This new function expects the second argument, returns another function, and so on, until all arguments have been supplied and the final result is computed.

Each function in the sequence remembers the arguments passed to it through closures, allowing the final function to access all necessary values to perform its computation.

Why Use Currying?

  • Reusability and Parameterization: Create specialized, reusable functions from more general ones by fixing some arguments. For instance, a general multiply function can be curried to create a multiplyByTwo or multiplyByTen function.
  • Delayed Execution: The function doesn't execute until all arguments are received. This is useful in scenarios where arguments become available at different times.
  • Function Composition: Curried functions are often easier to compose with other functions, leading to more readable and modular code.
  • Easier Argument Handling: Can simplify argument validation and default handling by processing one argument at a time.

Example

Let's consider a simple add function that takes two numbers and returns their sum.

javascript
function add(a, b) {
  return a + b;
}

console.log(add(2, 3)); // Output: 5

Now, let's curry this add function.

javascript
function curriedAdd(a) {
  return function(b) {
    return a + b;
  };
}

// Usage:
const addTwo = curriedAdd(2); // Partially applied function, 'a' is now fixed as 2
console.log(addTwo(3));      // Output: 5 (2 + 3)
console.log(addTwo(10));     // Output: 12 (2 + 10)

// Or call directly:
console.log(curriedAdd(5)(6)); // Output: 11

In this example, curriedAdd(2) returns a new function that 'remembers' a=2 through a closure. When addTwo(3) is called, b=3 is supplied, and the final sum is computed. This demonstrates how we can create a specialized addTwo function.

Currying vs. Partial Application

While often used interchangeably, currying is a specific form of partial application. Currying transforms a function f(a, b, c) into a chain of unary (single-argument) functions: f(a)(b)(c). Partial application, on the other hand, allows you to fix any number of initial arguments, returning a new function that takes the remaining arguments, e.g., f(a, __)(c) where __ is a placeholder for b.

Many utility libraries, like Lodash, provide a _.curry function that makes it easy to curry existing functions automatically.