Skip to content
Arif Mulani Sans Arif
Tags Search
Go back

Currying in JavaScript

In past few articles, we have seen topics around this keyword. Now let’s move to a functional programming technique called currying. Closures are the foundation of currying. If you are not familiar with closures, I recommend you to read my article on closures.

In this technique a function takes multiple arguments is transformed into a sequence of functions, each taking a single argument. Currying doesn’t call the function but transforms it.

// Before: all arguments at once
function add(a, b, c) {
  return a + b + c;
}
add(1, 2, 3); // 6

// After: one argument at a time (curried)
function curriedAdd(a) {
  return function(b) {
    return function(c) {
      return a + b + c;
    };
  };
}

curriedAdd(1)(2)(3); // 6

// We can also store the intermediate functions in variables
const curriedSum = curriedAdd(1);
curriedSum(2)(3); // 6

Each intermediate function takes one argument and returns a new function that waits for the next argument. The innermost function finally has access to all the arguments and produces the result. This chaning works because of closures.

Like Alia Atreides (ref: Dune), she has access to the memories of her ancestors. In the same way, each function in the chain has access to the arguments passed to its outer functions.

Building a generic curry utility

Manually currying every function by writing nested return function calls doesn’t scale. Look at the above example, if we have a function with 10 arguments, do you think writing it in above way will be a good idea? No, it will be a nightmare to write and hell to read.

function curry(func) {
  return function curried(...args) {
    if(args.length >= func.length) {
      return func.apply(this, args);
    } else {
      return function(...args2) {
        return curried.apply(this, [...args, ...args2]);
      }
    }
  }
}

Detailed breakdown of this code:

Directly diving into above code will give you migrane. So let’s break it down into smaller pieces and understand it.

  1. args.length: args is an array of arguments. So, it’s .length means number of arguments passed to the curried function.
  2. func.length: func is the original function that we are currying. So, it’s .length means number of parameters that the original function expects.
  3. func.apply(this, args): This line calls the original function with the current this context and the arguments passed to the curried function. It executes the original function when all required arguments are provided.
  4. curried.apply(this, [...args, ...args2]): This line calls the curried function recursively with the current this context and the combined arguments from both the outer and inner functions.

These four points are the key to understand how this curry utility works. Now, let’s see how we use these four points to implement the curry utility. Let’s do it in Q&A format.

Q1: What is the purpose of the curry function?

A1: Take a function as input and return a new function that can be called with one or more arguments at a time. So our curry function returns a new function called curried.

Q2: What is the purpose of the curried function?

A2: Check if number of arguments are enough to call original function. If, yes: Call the original function with all the arguments and return the result. If, no: Return a new curried function that already has the arguments passed so far and waits for more arguments before calling the original function.

Basically, return a new curried function with the arguments already passed so far and can be called with more arguments until the original function can be called when all required arguments are provided.

It supprots multiple calling styles

We can pass arguments in different ways: one-by-one, partially, or all at once.

function volume(l, w, h) {
  return l * w * h;
}
const curriedVolume = curry(volume);

const result1 = curriedVolume(2)(3)(4);   // 24 - one at a time
const curried1 = curriedVolume(2, 3);    // curried1 - a function that already has the first two arguments (2 and 3) stored
const result2 = curried1(4);             // 24 - continue with the remaining args
const result3 = curriedVolume(2)(3, 4);  // 24 - or at different steps
const result4 = curriedVolume(2, 3, 4);  // 24 - or all at once (just calls the original)

Alternative advanced curry (without using apply)

Before lokking at the alternative advanced curry implementation, let’s understand what apply is doing here (we can use call too).

Looking at the code you can see that apply is doing nothing but passing current this context and concatenating the arguments. You will be more worry about the this. How can we handle this. Let me remind you that this depends on how the function is called. So, we can completely ignore this in our curry implementation for now and come back if we get into some problem.

So, based on current implementation (using apply), if our original function is using this, then we’ll have to call the final curried function with correct this context. We’ll see this with an example but first take a look at alternative advanced curry implementation without using apply or call.

function advancedCurry(func) {
  return function curried(...args) {
    if(args.length >= func.length) {
      return func(...args);
    } else {
      return function(...args2) {
        return curried(...[...args, ...args2]);
      }
    }
  }
}

const add = (a, b, c) => a + b + c;
const curriedAdd = advancedCurry(add);

// Partial application
const addPartial = curriedAdd(1);
const result = addPartial(2)(3); // 6

// Full application
const fullResult = curriedAdd(1)(2)(3); // 6

It was not that advanced after all. Just handled argument concatenation correctly without using apply or call.

What if my original function is using this?

If we go back to our implmentation of curry using apply. Calling final curried function with correct this is giving us correct result.

function volume(l, w, h) {
  return this.multiplier * l * w * h;
}

const obj = { multiplier: 2 };

const curriedVolume = curry(volume);
const curried1 = curriedVolume(2, 3);
console.log(curried1.call(obj, 4)); // 48 - correct result with `this` context

Now, if we use advancedCurry here it will not give us result as expected. It will give us NaN as the line return func(...args); is calling the original function as stand-alone function and in that case it is undefined in strict mode or window object in browser. So we got into problem here.

We know for sure that value of this depends on how the function is called. Can we do something to make sure that the original function will get called with correct this context?

If you’ll go back to this section from previous article. Here our function’s reference was pushed into event queue and later executed without any context. We were losing the this context, so we used bind to bind the correct this context to the callback function permanently. Check bind section from previous article to understand it if you are not familiar or want to refresh your memory.

Now we can do same here:

const curriedVolume = advancedCurry(volume.bind(obj)); // permanently binding `obj` as `this` context
console.log(curriedVolume(2, 3)(4)); // 48 - correct result with `this` context

Note: Here original function (volume) is not bound to obj permamnently as bind returns a new function with this context bound to obj and not mutating the original function. So, if you call volume(2, 3, 4) it will give you NaN as this is not bound to obj permanently.


Limitations of currying

Currying is a powerful technique, but it has some limitations:

  1. Only works with fixed-length functions: The curry utility relies on func.length to know when enough arguments have been collected. Functions that use rest parameters (...args) or default parameters have length of 0 (or less than expected), so curry can’t determine when to stop collecting.
function sum(...nums) { 
  return nums.reduce((a, b) => a + b, 0);
}
console.log(sum.length); // 0 — curry won't work with this

function greet(name, greeting = "Hello") { 
  return `${greeting}, ${name}`;
}
console.log(greet.length); // 1 — default param not counted
  1. this context: We already ran into problem we write curry utility without using apply. Based on the implementation of curry utility, way of calling final curried function with correct this context gets determined.

I hope you have learned something new about currying in JS. Next article will be about Inheritance and protoype chaining. Meanwhile explore real-world use cases of currying and also about partial application which is closely related to currying.


Related posts