Write expressive JavaScript code using currying and objects

Max Dollinger
3 min readApr 20, 2021

Since in JavaScript everything is basically an object you can easily store functions as values in objects. Because of that you can use the object keys to “name” your functions and call them. With this and a bit of currying you can write very easy to read code. Let’s see how.

But first what is currying? Currying is mainly a thing in functional programming where a function with multiple arguments is turned into functions with one argument that returns a function that accepts the next argument and so on. Here is a simple example for a function that adds three numbers:

To curry this function we need to rewrite the code so that for each argument another function is returned who accepts the next argument. For the toCurry() function this looks like this:

Now lets use this to write very readable code.
To pick an easy example we’ll take a function that swaps to elements in an array. Normally the function would look something like this:

In this example we’re going full ES6. First we have an arrow function that accepts 3 arguments. The first argument is the array. Because arrays are reference types in JS we use the spread operator “…” to make a shallow copy of the array to not mutate the original one and name it arr. The second and third arguments are the indices we want to swap. Since ES6 it is possible to define two variables at the same time which we use here to swap the two elements. Finally the array with the swapped elements is returned. This looks ok but we maybe can do better. Because everything in JS is basically an Object even functions we can easily store functions in objects and access them via the dot operator. We can use this functionality in combination with currying to make the function call much more readable.

What happened here? First we call swap and pass the first index. This returns an object with one key with that holds another function. The second function accepts the second index as it’s argument and again returns an object with the key in and the third functions as it’s value. The third function accepts the array where we want to swap the elements as it’s argument, swaps them and returns the array. Now if we want to swap two elements the function call reads like an instruction swap(index1).with(index2).in(array).
Of course it’s possible to make it a bit shorter so that the function is called like swap(index1, index2).in(arr).

For a simple swap function this might be a bit of an overkill but it should showcase how you can use JS features to create very easy to read code.
And aside from producing very reader friendly code it’s always fun to tinker around with a programming language. So go and try it yourself.

--

--

Max Dollinger

I’ve studied a lot from law over geology to business IT. And lost my heart to programming. I life by the credo “always be curious and never stop learning”