javascripttypescript
What is a Curried Function?

min read
Photo by Sigmund (https://unsplash.com/@sigmund)

Let's start with a short explanation of what a curried function is:

A curried function is a function that takes multiple arguments one at a time.

Here's an example

Case:

A function called addTwo() that takes the following parameters: a and b and returns the sum.

Normal implementation:


    function addTwo(a: number, b: number) {
      const sum = a + b;
      return sum;
    }
    addTwo(9, 10) // 19

or the more concise ES6 arrow function way:


    const addTwo = (a: number, b: number) => a + b
    addTwo(9, 10) // 19

Curried implementation:


    function addTwoCurried(a: number) {
      return function (b: number) {
        const sum = a + b;
        return sum;
      }
    }
    addTwoCurried(9)(10) // 19

...and the arrow function way:


    const addTwoCurried = (a: number) => (b: number) => a + b
    addTwoCurried(9)(10) // 19

Taking curried functions to the next level

We can keep nesting functions like this (but it's ugly and I don't recommend it):


    const addManyCurried = (a: number) => (b: number) => (c: number) => (d: number) => (e: number) => a + b + c + d + e;
    addManyCurried(1)(2)(3)(4)(5) // 15