Add(1)(2)… (infinity)

Long Wallpapers

You probably already know that JavaScript is an incredibly flexible language. I would like to share one of my favourite examples of what it really enables you to do.

Lets begin with creating a function add that accepts two arguments, a and b and returns the sum:

const add = (a, b) => a + b;

Pretty straight forward; however, what if you would like to add the second number later? Say you would want to do the following:

var addFour = add(4);
addFour(2) // returns 6

It can actually be done with the help of a technique called currying, which turns out to be one of the cornerstones in functional programming. Don’t be scared, it is simpler than you think:

const add = (a) => (b) => a + b;

It basically returns a new function that addFour in the example above will reference to. I’ll make it crystal clear:

var addFour = add(4); // returns a function
addFour = (b) => 4 + b; // reference to function

Cool, huh?

However, wouldn’t it be more convenient to be able to do this indefinitely?

Impossible right? No, not in JS. It turns out we can alter the value of the function itself, to return a primitive value that is our sum. Combined with the ability to return functions we can easily write something along these lines:

const add = (sum) => {
const fn = (b) => add(sum + b);

fn.valueOf = () => sum;

return fn;

Now we can actually call the function like this:

add(2)(3)(4)(2) // returns 11
add(1)(2) // returns 3
add(3)(1)(4) + 3 // returns 11

I hope you enjoyed the reading! :)