Ian Walton Ian Walton

Clean JavaScript: Currying

Introduction

Currying is a powerful tool that leverages partial application of parameters to create pure higher-order functions that can be composed to build complex JavaScript applications.

Currying in Practice

Consider this example of a typical function comparing a widget’s price:

const isWidgetUnderMaxPrice = (widget: Widget, maxPrice: number) => {
    return widget.price < maxPrice;
};

This method could be called in a variety of places and with different prices:

// foo.js
isWidgetUnderMaxPrice(widget, 500);

// bar.js
widgets.filter((widget) => isWidgetUnderMaxPrice(widget, 1000));

With currying, we’re able to abstract away the constant and enrich the domain language of our application:

const isWidgetUnderMaxPrice = (maxPrice: number) => {
    return (widget: Widget) => {
        return widget.price < maxPrice;
    };
};

const isWidgetPriceUnder500 = isWidgetPriceUnderMaxPrice(500);
const isWidgetPriceUnder1000 = isWidgetPriceUnderMaxPrice(1000);

// foo.js
isWidgetPriceUnder500(widget);

// bar.js
widgets.filter(isWidgetPriceUnder1000);

Explanation

Currying works through a process called partial application where a function with a higher arity (the number of parameters) can be invoked to create smaller functions at different points in the application lifecycle. This feature is particularly useful when creating pure functions that can be composed into complex algorithms, like using Lego blocks build the Death Star.

Conclusion

I hope this has helped you understand what currying is and how valuable it can be in an application. Try it out and let me know what you think!