Course contentsShow
← JavaScript
Lesson 1765 of 2,72337. Functional Programming PatternsFree lesson

Manual Currying Example

Write a curried function by hand to understand the nested structure and closure mechanics.

Manual Currying Example

You'll learn how to write a curried function by hand to see exactly how closures create the nested structure.

The Core Idea

In the previous lesson, you learned what currying is conceptually. Now let's build one manually to understand the mechanics. A curried function returns nested functions, each accepting one argument and remembering previous arguments through closures.

Building a Curried Function Step-by-Step

Let's take a simple function that adds three numbers and curry it manually:

// Original function
function add(a, b, c) {
  return a + b + c;
}

// Manually curried version
function curriedAdd(a) {
  return function(b) {
    return function(c) {
      return a + b + c;
    };
  };
}

// Usage
const result = curriedAdd(2)(3)(5); // 10

How It Works

Each function layer:

  1. Accepts one parameter
  2. Returns another function (except the innermost one)
  3. Remembers all previous parameters via closure

When you call curriedAdd(2), it returns a new function that "remembers" a = 2. When you call that with (3), it returns yet another function remembering both a and b. Finally, calling with (5) executes the actual calculation.

The Power of Partial Application

You can save intermediate steps:

const addTwo = curriedAdd(2);
const addTwoAndThree = addTwo(3);
const final = addTwoAndThree(5); // 10

Each step creates a specialized function, holding onto the arguments provided so far.

Key Takeaway: Manual currying uses nested functions where each level returns the next function and captures arguments through closures, creating a chain where arguments accumulate until the final computation executes.