JavaScript Currying

The first time I heard the term Currying was during a job interview preparation. Fortunately, the interviewer did not ask me any questions about it.

Do you know what currying is? This simple concept can greatly simplify our code logic.

What is Currying?

Currying is an advanced technique used with functions.

It transforms a function that takes multiple arguments (e.g., f(a, b, c)) into a series of functions that can be called one after another (e.g., f(a)(b)(c)).

Currying doesn't execute the function immediately; it merely transforms it.

Basic Example

Let's start with a simple example. Suppose we have a function sum(a, b) that adds two numbers.

In most cases, we directly call this method to obtain the result, like this:

function sum (a, b) {
  return a + b;

console.log(sum(4, 5)); // Output: 9

Now, let's change it to the currying approach:

function sum(a) {
  return function(b) {
    return a + b;

console.log(sum(4)(5)); // Output: 9

In this example:

  1. The sum function takes the first number a as the parameter.
  2. It returns a new function that accepts b.
  3. The finally result will be caculated after the new function calling.

Subscribe to read the full content