Currying transforms a function that takes multiple arguments into a chain of functions each taking a single argument. Partial application fixes some arguments upfront and returns a function waiting for the rest.
Think of currying like ordering a custom sandwich. Instead of saying "lettuce, tomato, mayo" all at once, you tell the chef one ingredient at a time. Each time you say an ingredient, they hand you back a partially-built sandwich. Only when all ingredients are specified do you get the complete sandwich. Partial application is saying "lettuce and tomato" upfront and getting back a sandwich that's just waiting for mayo.
Both build on closures and are foundational to functional programming.
Prerequisites: JS Foundations #3 — Closures
1. What is Currying?
Currying converts f(a, b, c) into f(a)(b)(c) — each call returns a new function until all arguments are collected:
Loading editor...
Each intermediate function "remembers" its argument via closure until the final call.
2. Implementing a Generic curry()
Write a function that curries any n-argument function:
Loading editor...
The fn.length check uses the function's declared parameter count to know when we're done collecting. Important: fn.length counts only the parameters before the first default value or rest parameter. So (a, b, c) => {} has length 3, but (a, b = 1, c) => {} has length 1, and (...args) => {} has length 0. For functions with rest parameters or defaults, you'll need a different stop condition (like the empty-call terminator shown in Section 3).
3. Infinite Currying — sum(1)(2)(3)()
A classic interview question: create sum that accumulates until called with no arguments:
Loading editor...
4. Partial Application — Fix Arguments Upfront
Partial application is like bind but without touching this:
Loading editor...
5. Currying vs Partial Application
They look similar but serve different purposes:
Loading editor...
| Currying | Partial Application | |
|---|---|---|
| Arguments per call | Strictly one (or any, in JS-style curry) | Any number |
| Return type | Curried function until all args collected | Returns a function immediately |
| Use case | When you want point-free composition | When you want to fix known args now |
6. Real-World Use Cases
Loading editor...
Key Takeaways
- Currying transforms
f(a,b,c)→f(a)(b)(c)— each call returns a function until all arguments are supplied. fn.lengthtells you how many parameters a function declares — the stop condition for curry.- Infinite currying uses a terminator (empty call
()) orvalueOf/toStringoverload. - Partial application is like
bindwithoutthis— pre-fill arguments, get a function back. - Currying shines in point-free composition; partial application shines when you know some args now but not all.
