Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Refactor a Function to Use Currying in JavaScript

    Kyle ShevlinKyle Shevlin

    This lesson teaches you what currying is: the act of refactoring a function so that it receives its arguments one at a time. We will use the canonical example of an add function to demonstrate this. This lesson also teaches the concept of “arity”, the number of arguments a function receives, as it is useful knowledge for functional programming.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: currying is the act of taking a function that normally receives more than one argument such as add and refactoring it so that it becomes a higher-order function that returns a series of functions each accepting only one argument and only evaluating once we receive our final argument.

    If I try using add function the normal way by passing both variables in at the same time, and I log that out, all I'll get back is a function. This happens because the second variable is ignored and we receive back the function that's been returned on line four.

    Instead, I can save the return function as a new variable. In this case, we'll call it add 3. I can now take our new function and give it its final argument. I can reuse this function. I'll call it several times with different numbers. If I log this out, I get the correct summation. Every function and functional programming is curried like this.

    We can write our curried functions much more succinctly using an ES2015 arrow function. Arrow functions implicitly return each expression that comes after an arrow. In this case, we return this full function after receiving our X. After receiving our Y, we return the evaluation of X+Y.

    At this point, I want to briefly discuss some jargon. That is the word arity. Arity describes the number of arguments a function receives. Depending on the number it receives, there are specific words to describe these functions.

    A function that receives one is called a unary function. A function that receives two arguments is called a binary, three equals a ternary, and four equals a quaternary, so forth and so on. Thus the act of currying can be described as taking a multivariate function and turning it into a series of unary functions.