What is function currying and why you should care

scottstern06

Scott

Posted on April 20, 2020

What is function currying and why you should care

There are a lot of patterns in Javascript but I find this one particularly useful.

The pattern is function currying. Learning this concept helped me get a better understanding of the power of the language and functions in Javascript.

What is function currying?

This is when you create a function, that simply returns another function.

Easy, right?

const curry = () => {
  return () => {
    return 'Some Value';
  }
}
Enter fullscreen mode Exit fullscreen mode

Why should you care?

Learning this pattern allows you to make your programs more flexible, cleaner, easier for fellow developers to consume, and easier to test (I wont go into all of these in this blog post).

Example time!

Let's say I know I'll need to add something. Maybe I'll need to add something by 1, 3, ....

We can use currying for this

const add = (x) => {
  return (y) => {
    if (y !== undefined) {
      return x + y;
    }

    throw new Error('Please provide an number as an argument');
  }
}
Enter fullscreen mode Exit fullscreen mode

So then we can use this in our code.

const addOne = add(1); // addOne is just a function at this point, console.log it, I know you want to.

addOne(2) // returns 3

addOne(); // UH OH...Error thrown, because we're good developers and provide feedback to using our functions!

const addFive = add(5);

addFive(1); // returns 6
Enter fullscreen mode Exit fullscreen mode

Now, everyone is an expert in function currying in Javascript, let's move on.

But Scott! Whats the difference between this and higher order functions.

Great Question!!!! Simply put HOF take a function as an argument while function currying is when a function returns a function. If you want to learn more about this, comment below!

A lot of this patterns power comes from flexibility, but also, leveraging closures to isolate and access variables in scope.

From our example above:

const add = (x) => {
  return (y) => {
    if (y !== undefined) {
      return x + y;
    }

    throw new Error('Please provide an number as an argument');
  }
}
Enter fullscreen mode Exit fullscreen mode

We can access x from inside the return function at a later date if needed, but still holding onto its value when it was first invoked. This can be useful when iterating over large lists and needing to reference some specific data in one of the rows at a later point in time.

Paste some use cases below for others to see how this is used in the wild! I would love to see them!

Thanks for reading and I hope you'll now feel comfortable enough to use this pattern next time you're working on a problem.

💖 💪 🙅 🚩
scottstern06
Scott

Posted on April 20, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related