Currying in Javascript (tersely explained)

const add = (a,b) => a+b
const adder = a => b => a+b
const curry = fn => a => b => fn(a,b)
// curry(add) is identical to adder

TL;DR Summary

How are the above functions related?

  • adder is a higher-order function with unary inputs: adder(2)(3)
  • curry transforms add into adder
  • enables the use of closures
  • can be extended for an arbitrary number of inputs
  • TOPICS: Higher-order functions, closures, partial application, currying, functional programming

Introduction

Currying is a somewhat advanced technique that has a simple precept — it converts a function that takes multiple arguments into a sequence of functions that each take a single argument.

const add = (a,b) => a+b
add(2,3) // 7

Higher-Order Functions

But we may want to encapsulate a in a closure, and leave b as the only input — say we want to add 5 to any given number — add5(b) returns b+5. Variable a is "enclosed" in function add1 .

const adder = a => b => a+b
adder(5)(4) // 9
const add5 = adder(5)
add5(4) // 9

Currying

How do we transform add() into adder()()? You may have guessed the answer...!

const curry = fn => a => b => fn(a,b)// direct usage
curry(add)(5)(7) // 12
// with closure
add5 = curry(add)(5)
add5(7) // 12
  • We have an adder high-order function
  • Currying let’s us use add in the same way as adder. In the example here, we created a simple closure
const curryRev = fn => b => a => fn(a,b)
// a and b are declared in reverse order
const pow5 = curryRev(Math.pow)(5)
pow5(2) // 32

Partial Application

This is a bit redundant by this point, but throughout we have been using partial application of functions. A partial application is a function which has had some, but not yet all, of its arguments applied.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store