← Go back

The Simplest Intro to Currying in JavaScript

· 2 min read

Perhaps the oldest yet powerful technique of Functional Programming — Currying, which is basically the method of memoizing some of the function arguments and postponing its call until it gets all parameters.

An example of currying an add function that takes 3 arguments and can be called in several ways.


Getting Started

Theoretical part

So when you curry a certain function with N parameters, and if you call it with M parameters, where M < N, it returns a new curried function, which memoizes already passed M parameters and expects the rest of the needed parameters (“N — M”).

NOTE: Currying of a function can be repeated not only once, but as many times as needed until it gets all parameters.

Practical part

So let’s take a look at an actual implementation:

/** ===== IMPLEMENTATION ====== */
function curry(fn) {
    return function curriedFn(...args) {
        if (fn.length !== args.length) {
            return curriedFn.bind(null, ...args);
        }
        return fn.apply(null, args);
    };
}

/** ========= USAGE ========== */
const TEXT = 'Oh my God, it just works.'
const replace = curry((regex, sub, text) => text.replace(regex, sub));

// Example 1
const replaceVowels = replace(/[aeiou]/ig)
const asteriskVowels = replaceVowels('*')
const dollarVowels = replaceVowels('$')

console.log(asteriskVowels(TEXT)) // *h my G*d, *t j*st w*rks. 
console.log(dollarVowels(TEXT)) // $h my G$d, $t j$st w$rks.

// Example 2
const shout = replace(/\.+/g, '!')
console.log(shout(TEXT)) // Oh my God, it just works! 

A few things to note:

  • fn.length — we are just using Function.length JS feature, which indicates a number of parameters expected by the function.

NOTE: It counts until the first parameter with a default value or until rest parameters.

  • curriedFn.bind(null, ...args) — here we are returning another curriedFn, but now we actually are saving already passed parameters using Function.prototype.bind(). So next time curriedFn will be called with new parameters, old parameters will be prepended to new ones.

Summary

Currying is a very handy technique that allows us to create useful functions on the fly by passing fewer parameters. Hopefully, now you know how currying works or at least have a better understanding of it.

Going further, currying is originally from the Functional Programming world and that’s why when you use it you unintentionally write a kind of declarative expressions instead of imperative instructions. Currying best works with other FP-related paradigms, like function composition.

More articles coming in continuation of FP topic…

— P.S: If you find this article interesting, feel free to follow me on Medium as well as on Twitter.

© 2022 Erzhan Torokulov