---
title: Function Currying in CoffeeScript
teaser: |
  Convert a CoffeeScript function that takes multiple arguments
  into a chain of functions that take one argument each.
  This is called function currying,
  and it can make your easier to understand!
tags: web,javascript
author: Sage Griffin
published_on: 2014-02-12
---

Have you had a function that takes two arguments, but you want to pass the
second argument in later? Here's one possible example:

```coffeescript
updateUsers = (db, users) ->
  _.map(users, (user) -> updateUser(db, user))

updateUser = (db, user) -> db.update("users", name: user.name)
```

This is messy, and extremely hard to parse mentally. However, we can make this
a bit cleaner using [function currying][currying]. Originally worked out by
Haskell Curry, function currying is the act of taking a function that takes
multiple arguments, and replacing it with a chain of functions that take a
single argument each.

Curried functions take advantage of [closures] to emulate multiple
arguments. In some functional languages, such as [Haskell] or the
[lambda calculus][lambda-calculus], curried functions are the only way to
pass multiple arguments to functions.

If we curry our `updateUser` function, our code becomes much more readable.

```coffeescript
updateUsers = (db, users) ->
  _.map(users, updateUser(db))

updateUser = (db) -> (user) -> db.update("users", name: user.name)
```

The resulting JavaScript for our `updateUser` function will look like this:

```javascript
var updateUser = function(db) {
  return function(user) {
    return db.update("users", { name: user.name });
  };
};
```

It's a simple trick, but a prime example of how CoffeeScript's syntax can make
certain tasks much cleaner!

[currying]: http://en.wikipedia.org/wiki/Currying
[closures]: http://en.wikipedia.org/wiki/Closure_(computer_science)
[Haskell]: http://www.haskell.org/haskellwiki/Haskell
[lambda-calculus]: https://trylambda.com/
