Currying in Javascript

December 02, 2021

Currying can help keep our code dry and maintainable. According to Wikipedia

In mathematics and computer science, currying is the technique of converting a function that takes multiple arguments into a sequence of functions.


Basic Example
// basic add function
function add(x, y, z) { 
    return x + y + z
}

// the curry function
function addPartial(x) {
    return function(y,z) {
        return add(x,y,z)
    }
}

const add5 = addPartial(5); //x value
const sum = add5(7, 8)  //y,z values

console.log(sum)
> 20

So if we log out our add5 const, you can see it returns the following function which is essentially a closure

console.log(add5)
> function(y,z) {
      return add(x,y,z)
  }

we could also just call addPartial like the following and get the same sum of 20

addPartial(5)(7,8);

es6 syntax

const add = (x, y, z) => x + y + z
const addPartial = (x) => (y,z) => add(x,y,z)

© 2022, Built by Ron Pruitt using Gatsby