Currying Functions in JavaScript

Ignacio Ojanguren
2 min readNov 13, 2021

--

JavaScript Functions

Currying can sound very confusing on how it works, and when it should be used. Let me give a quick definition on how Currying works before I give you an example

Currying is a way to break a function with multiple arguments, into multiple functions with single arguments.

const adding = (a, b) => { return a + b }
console.log(adding(1, 2))
// Currying is breaking the function into multiple functions
// with single arguments
const adding = (a) => {
return (b) => {
return a + b
}
}
console.log(adding(1)(2))

— You may be asking yourself. What is the point on doing this? Doesn’t this make the code more confusing?

— I would disagree with you here.

When you use Currying it helps you organize and cleanup your code, as well as making it easier to extend.

What I like to think if I am not sure if a function should use Currying or not is, if one of the parameters of the function is going to be the same across multiple function calls you can probably use Currying.

Let me show an example with a basic API request example, where we are going to use axios to make a GET request:

const getRequest = (url) => (data) => (
axios.get(url, { params: data })
.then((response) => response.data)
)
const userRequest = getRequest('http://userurl.test')
const userInformation = userRequest('email@testing.com')
const businessRequest = getRequest('http://businessurl.test')
const businessInformation = businessRequest('mybusiness@business.com')

Now, in order to prove you how easy it would be to extend the function from above getRequest, let me ask you this question. How would you modify this function to make it more generic? Meaning not only a GET request, but also a POST, UPDATE, or DELETE requests. Remember to use Currying, and Axios API.

Take a few minutes to think about the best way to refactor the function from above.

Feel free to type your answer down in the comments.

Ok. Here it is how I would refactor this function.

const makeRequest = (method) => (url) => (data) => (
axios({
method,
url,
data
}).then((response) => response.data)
)
// Create GET request
const getRequest = makeRequest('GET')
const userRequest = getRequest('http://userurl.test')
const userInformation = userRequest('email@testing.com')
const businessRequest = getRequest('http://businessurl.test')
const businessInformation = businessRequest('mybusiness@business.com')
// Create POST request
const postRequest = makeRequest('POST')
const createUser = postRequest('http://newuserurl.test')
const newUser = createUser({ email: 'email@testing.com' })

What do you think about this implementation?

--

--

Ignacio Ojanguren

Over 3 years of experience as a Software Engineer at Privy, recently acquired by Attentive Mobile. I am Learning, and I hope I can share what I learn with you.