What Is Currying in JavaScript and Why Does It Matter?

Currying is a topic that often sits in the more advanced user circles of JavaScript. It extends beyond the usual usage of functions and methods and starts to dive into the structural side of code.

When you start to build more complex applications, you start looking into your toolbox for architecture and structural knowledge kit sets to help keep your team’s code sanity intact and ensure a certain level of clean code. Currying is one of these methodologies.

So what is currying? How does it work? Why does it matter? And how do you apply it in your functions?

But before we get into all that, we need to first talk about functional programming.

A Quick Primer on Functional Programming

By design, JavaScript is multi-paradigm. This means that it doesn’t conform to just one single pattern of coding. You can mix and match from a range of patterns, and functional patterns are one of them.

When we start learning about code, we’re often told that everything is an object. But the truth is not everything is an object. There are certain things that just simply don’t fit into the object-oriented way of thinking.

Functional programming is a style of writing code that involves a pattern of passing functions as arguments and the ability to return functions without causing side effects.

Immutability is one of functional programming’s best features.

The ability to pass and return functions is done through one of three concepts: pure functions, higher-order functions, and currying.

What Is Currying?

No, we’re not talking about the Indian spice. Rather, we’re talking about the process where a function takes multiple arguments one at a time.

So rather than having a function that looks like this:

fakeFunction('param1', 'param2', 'param3');

You end up with something like this:

fakeFunction('param1')('param2')('param3');

What happens here is that when you pass in a parameter, the first function processes it, then returns a function that processes the next parameter. This lets you chain your arguments in a way that prevents it from having any side effects.

How?

When you apply functional programming ideas to your code, your function does one thing and one thing only: It results in an output that can’t be disputed. The shape of your data doesn’t change. Mutability caused by side effects is reduced to zilch.

When you have more than one argument, you’re setting yourself up for potential side effects. However, when you curry your code, your first argument returns an expected outcome that proceeds to process your next argument, and so on and so forth.