JavaScriptMedium
What is currying?
Currying transforms a function that takes several arguments into a chain of functions that each take one argument, so f(a, b, c) becomes f(a)(b)(c); it is mainly used to create specialised functions by fixing some arguments up front.
Why it is useful
- Configuration first, data last:
const formatPrice = format("en-US")("USD")creates a reusable helper; you then callformatPrice(19.99)many times. - Point-free composition: curried, single-argument functions plug neatly into
map,filterandpipe. - Event handlers:
onClick={select(item.id)}whereselect = (id) => (event) => ....
Currying vs partial application
- Currying always produces unary functions, one argument at a time.
- Partial application fixes some arguments and returns a function expecting the rest, any number at once.
fn.bind(null, a)is partial application. In everyday JavaScript the two are often used interchangeably, and "curry" helpers usually accept several arguments per step.
Trade-offs
- Can make code elegant in functional pipelines.
- Can make stack traces and signatures harder to read if overused.
- Generic
curryhelpers rely onfn.length, which does not count rest or default parameters.
Interview angle
Expect "implement curry(fn)", where the trick is collecting arguments until there are fn.length of them (see the "Implement currying" question).
Code example
js
1// Manual currying with arrow functions2const multiply = (a) => (b) => a * b;3const double = multiply(2);4console.log(double(21)); // 425console.log([1, 2, 3].map(multiply(10))); // [10, 20, 30]67// Configuration first, data last8const formatCurrency = (locale) => (currency) => (amount) =>9 new Intl.NumberFormat(locale, { style: "currency", currency }).format(amount);10const usd = formatCurrency("en-US")("USD");11const eur = formatCurrency("de-DE")("EUR");12console.log(usd(1234.5), "|", eur(1234.5)); // $1,234.50 | 1.234,50 €1314// Event-handler style15const handleSelect = (id) => (event) => `selected ${id} via ${event.type}`;16console.log(handleSelect(7)({ type: "click" })); // selected 7 via click1718// Partial application with bind (not strictly currying)19function greet(greeting, name) {20 return `${greeting}, ${name}`;21}22const hello = greet.bind(null, "Hello");23console.log(hello("Ada")); // Hello, Ada
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.