How I Got Into JavaScript Function Currying

June 14, 2016

It started out as I was doing a code kata. I saw some function call that looked like the following:

magicAdder(2)(3) // returned 5
magicAdder(2, 1) // returned 3

I had never seen anything done like that in Ruby. I didn’t even know what that was called, so I had no idea what to Google for. But eventually I found the name….JavaScript function currying.

What is JavaScript Function Currying?

JavaScript function currying is partial function evaluation. In practice this means you can pass a subset of the arguments a function is expecting and you’ll get back a function that will fire once it’s received the rest of the arguments.

Example 1 – Basic Currying

function doubleHello(message1) {
  return function(message2) {
    console.log('Message1: ' + message1 + ' Message2: ' + message2);
  };
}
doubleHello('msg1')('msg2'); // Message1: msg1 Message2: msg2
var v = doubleHello('msg1'); // [Function]
v('hello world'); // Message1: msg1 Message2: hello world

Example 2 – Curried Multiplication

function mult(x, y) {
  if (arguments.length < 1) {
    return mult;
  } else if (arguments.length < 2) {
    return function(z) {
      return x * z;
    };
  } else {
    return x * y;
  }
}

In Example 2 above, you can make the following types of calls and get a product back:

mult(2,2) //returns 4

mult(2)(3) //returns 6

Converting JavaScript arguments object to array

Another fairly common JavaScript idiom I saw at first was the following:

Array.prototype.slice.call(arguments);

This basically converts the default JavaScript arguments object (which you can access in any function body) into a JavaScript array with all the usual properties and methods.

Douglas Crockford gives a much more thorough and detailed explanation of function currying on his blog at http://javascript.crockford.com/www_svendtofte_com/code/curried_javascript/


Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.