With the rise of functional programming in software development, curried functions have become common in many JavaScript applications and it’s important to understand what they are and how to use them the right way.

Currying is a technique of translating a function with multiple arguments, into sequence of functions with single argument. In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function, and so forth, until all arguments have been fulfilled.

This technique is a fundamental tool in functional programming, a programming pattern that tries to minimize the number of changes to a program’s state (known as side effects) by using immutable data and pure functions (no side effects).

In the example below we have a function add that takes the first argument a and returns a function. This function is then executed with argument b and it returns the sum a + b. You can see below both ways of doing it:

// Regular version
const add = (a, b) => a + b;

// Curried version
const add = a => b => a + b;

const result = add(2, 3); // => 5
const result = add(2)(3); // => 5

To better understand what’s going on in the curried version of the code, we need to understand the concept os Scopes and Closures in JavaScript, here’s a quick explanation.

The add function takes one argument, and then returns a partial application of itself with a fixed with value 2 in the closure scope.

That means that when we run the first part of the curried version, the return we get has the variable a A closure is a function bundled with its lexical scope. Closures are created at runtime during function creation. Fixed means that the variables are assigned values in the closure’s bundled scope.

What this means is, when we execute add(2), we return a function like this:

const add = (b) => 2 + b;

This gives us the ability to do this:

const addTwo = add(2);

const result1 = addTwo(3); // => 5
const result2 = addTwo(4); // => 6
const result2 = addTwo(10); // => 12

Summary

Currying allows us to easily get partials. As we’ve seen in the example, after currying we get a function that takes whatever number you input and sum with the number provided on the first argument call. And this can be reused like a factory.

What makes this possible in JavaScript is the concept of Scope and Closures. Its ability to retain the state of functions already executed, gives us the ability to create factory functions — functions that can add a specific value to their argument.

It can be a little overwhelming at first, specially for beginners but with time and practice it all you’ll finally get a hold on it and once you do that, coding will never be the same.

Leave a comment

Leave a Reply