Currying is one of functional programming's most powerful ideas — and one of JavaScript's most-asked interview topics. This guide builds your mental model from the ground up: function arity, partial application, fixed and infinite currying, placeholder arguments, compose and pipe, async pipelines, and 7 interactive problems to cement the knowledge.
Function ArityPartial ApplicationCompose & PipePlaceholdersAsync Pipelines7 Problems
What is Currying?
Currying is the technique of transforming a function that takes multiple arguments into a sequence of functions that each take a single argument. A curried fn(a, b, c) becomes fn(a)(b)(c).
The name comes from Haskell Curry, the mathematician who formalised the concept (though Moses Schönfinkel discovered it first). In Haskell the language, every function is automatically curried. In JavaScript, we implement it explicitly.
example.js
// Normal function
function add(a, b) {
return a + b;
}
add(1, 2); // 3
// Manually curried
function curriedAdd(a) {
return function(b) {
return a + b;
};
}
curriedAdd(1)(2); // 3
// Arrow syntax — same thing
const add = a => b => a + b;
add(1)(2); // 3
Key Insight
Currying is not calling the function — it is transforming it. The curried version is a new function that collects arguments one at a time. The original function is never called until all arguments have been gathered.
The mental model: each call "locks in" one argument and returns a new function waiting for the next. Think of it as progressively configuring a function before firing it.
Currying vs partial application — these are often confused. True currying always takes exactly one argument per call. Partial application pre-fills any number of arguments at once, producing a function that takes the remaining ones. Libraries like Lodash and Ramda implement the more flexible version that supports both.
Arity is the number of arguments a function expects. JavaScript exposes it as fn.length.
Arity types
Nullary (arity 0)
() => 42
Unary (arity 1)
x => x * 2
Binary (arity 2)
(a, b) => a + b
Ternary (arity 3)
(a, b, c) => ...
Variadic (arity n)
(...args) => ...
example.js
function add(a, b) { return a + b; }
add.length; // 2 — binary
const triple = (a, b, c) => a + b + c;
triple.length; // 3 — ternary
// Rest params count as 0 in fn.length — important for curry!
function sum(...args) { return args.reduce((a, b) => a + b, 0); }
sum.length; // 0 ← curry cannot infer arity from this
Why arity matters for currying
A curry implementation reads fn.length to know how many arguments to collect before calling the original function. If fn.length is 0 (variadic or default-param-only functions), the automatic curry cannot determine when to stop — you must pass the arity explicitly.
example.js
// fn.length is unreliable with default params
function greet(name, greeting = "Hello") { return `${greeting}, ${name}!`; }
greet.length; // 1 — only non-defaulted params count!
// Explicit arity workaround
curry(greet, 2)("Alice")("Hi"); // "Hi, Alice!"
Warning
Default parameters and rest parameters both reduce fn.length to less than the total number of parameters. Always test your curried function's .length before relying on automatic arity detection.
Partial application
Partial application creates a new function by pre-filling some — but not all — arguments of an existing function. Unlike currying (one arg at a time), you can lock in any number of arguments at once.
Partial ApplicationPartial application: function with 3 param slots partially applied with 1 arg, then called with remaining 2
Partial Vs CurryPartial application vs full curry: same result, different API
2. How Currying Works Internally
Curry is built entirely on closures. Each intermediate function closes over the arguments collected so far, accumulating them until the original function's arity is satisfied.
The accumulator pattern
example.js
function curry(fn) {
return function curried(...args) {
// Have we collected enough arguments?
if (args.length >= fn.length) {
// Yes — call the original function
return fn.apply(this, args);
}
// No — return a new function that closes over args collected so far
return function(...moreArgs) {
return curried.apply(this, args.concat(moreArgs));
};
};
}
// Usage
function add(a, b, c) { return a + b + c; }
const curriedAdd = curry(add);
curriedAdd(1)(2)(3); // 6 — one arg at a time
curriedAdd(1, 2)(3); // 6 — grouping allowed
curriedAdd(1)(2, 3); // 6 — grouping allowed
curriedAdd(1, 2, 3); // 6 — all at once
Line-by-line walkthrough
curry(fn) returns curried — a wrapper that checks how many arguments it has received so far.
if (args.length >= fn.length) — if the number of collected arguments is enough to satisfy the original function, call it immediately via fn.apply(this, args). Using apply preserves the this context.
Otherwise, return a new anonymous function. This function closes over args (the arguments so far) and when called with moreArgs, it calls curried again with the combined argument list. This is the recursion that drives accumulation.
Key Insight
Every curried intermediate function IS a closure. It closes over args — the partially-applied arguments from all previous calls. Currying and closures are inseparable; you cannot implement one without the other.
The fn.length edge cases
example.js
// Default params: fn.length under-counts
function f(a, b = 10, c) {}
f.length; // 1 — only 'a' counted (b has default, c comes after)
// Rest params: always 0
function g(...args) {}
g.length; // 0
// Destructured params: count as 1 each
function h({ x, y }, z) {}
h.length; // 2 — the destructured object counts as one param
// Solution for variadic functions: pass arity explicitly
function curryN(fn, arity = fn.length) {
return function curried(...args) {
if (args.length >= arity) return fn.apply(this, args);
return function(...more) { return curried.apply(this, args.concat(more)); };
};
}
const sumN = curryN((...args) => args.reduce((a, b) => a + b, 0), 3);
sumN(1)(2)(3); // 6
3. Fixed-Arity Curry
The classic curry implementation works when the function's arity is known and reliable — i.e., fn.length returns the correct count. This covers the vast majority of real functions: binary, ternary, quaternary, etc.
Flexible grouping
The implementation above already supports grouping — you can pass multiple args at once as long as the total eventually reaches fn.length. This is more useful in practice than strict one-arg-at-a-time currying.
example.js
const curry = fn => {
const arity = fn.length;
return function curried(...args) {
if (args.length >= arity) return fn(...args);
return (...more) => curried(...args, ...more);
};
};
// All of these are equivalent:
const add3 = curry((a, b, c) => a + b + c);
add3(1)(2)(3); // 6
add3(1, 2)(3); // 6
add3(1)(2, 3); // 6
add3(1, 2, 3); // 6
// Real-world: configurable logger
const log = curry((level, prefix, message) =>
`[${level}] ${prefix}: ${message}`
);
const warn = log("WARN");
const warnApp = warn("App");
warnApp("Something went wrong"); // "[WARN] App: Something went wrong"
const errorDb = log("ERROR", "DB");
errorDb("Connection failed"); // "[ERROR] DB: Connection failed"
Tip
The arrow-function version ((...more) => curried(...args, ...more)) is more concise but loses this context. Use the function keyword version when currying methods that use this.
What if the function should accept any number of arguments and you want to keep adding more indefinitely? Fixed-arity curry cannot help here — there is no fn.length to aim for. You need an explicit termination signal.
Empty-call trigger
The classic pattern: keep collecting args until the function is called with no arguments (an empty call). That signals "I'm done, give me the result."
example.js
function infiniteCurry(fn) {
const accumulated = [];
function collect(...args) {
if (args.length === 0) {
// Empty call — we're done collecting, call the original
return fn(...accumulated);
}
// More args — push them and return collect for the next call
accumulated.push(...args);
return collect;
}
return collect;
}
// Usage: sum all numbers via chaining
const sum = infiniteCurry((...nums) => nums.reduce((a, b) => a + b, 0));
sum(1)(2)(3)(); // 6
sum(1, 2)(3, 4)(5)(); // 15
sum(10)(); // 10
// Stateless version (no shared accumulated array — safe for multiple uses)
function infiniteCurry(fn) {
return function collect(...args) {
if (args.length === 0) return fn(...args);
return (...more) => (more.length === 0 ? fn(...args) : collect(...args, ...more));
};
}
const sum = infiniteCurry((...nums) => nums.reduce((a, b) => a + b, 0));
sum(1)(2)(3)(); // 6
The valueOf trick
Some implementations override valueOf and toString on the returned function so that it evaluates automatically in numeric or string contexts — no empty call needed.
example.js
function infiniteSum(a) {
let total = a;
function add(b) {
total += b;
return add; // return itself for chaining
}
// Override valueOf so the function coerces to a number in arithmetic
add.valueOf = () => total;
add.toString = () => String(total);
return add;
}
infiniteSum(1)(2)(3) + 0; // 6 (uses valueOf)
`${infiniteSum(4)(5)}`; // "9" (uses toString)
+infiniteSum(1)(2)(3)(4); // 10 (unary + triggers valueOf)
// Note: == comparison triggers valueOf; === does NOT
infiniteSum(1)(2)(3) == 6; // true
infiniteSum(1)(2)(3) === 6; // false (function !== number)
Warning
The valueOf trick works with ==, template literals, and arithmetic operators but fails with ===. Interview problems usually ask for the == version, but in production code prefer the explicit empty-call pattern for clarity.
The curry implementations so far already support grouping. The more permissive "lodash-style" curry merges argument groups at each step — curry(fn)(a, b)(c) works exactly like curry(fn)(a)(b)(c).
The merging implementation
example.js
// Same as our fixed-arity curry — grouping is already built in
function curry(fn) {
return function curried(...args) {
// args.length could be 0, 1, 2, ... — all grouped together
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function(...more) {
return curried.apply(this, args.concat(more)); // merge groups
};
};
}
// Three-argument function
const clamp = curry((min, max, value) => Math.min(max, Math.max(min, value)));
// All equivalent:
clamp(0)(100)(42); // 42
clamp(0, 100)(42); // 42
clamp(0)(100, 42); // 42
clamp(0, 100, 42); // 42
// Useful: pre-configured validators
const clamp0to100 = clamp(0, 100);
[120, -5, 50].map(clamp0to100); // [100, 0, 50]
Ramda.curry and lodash _.curry
Both Ramda and lodash implement this flexible curry. Ramda additionally supports placeholder arguments (covered in the next section). The key difference from a plain partial application utility is that curry keeps returning new functions until the arity is fully satisfied — you never need to know in advance how many arguments remain.
example.js
// lodash _.curry example
import _ from "lodash";
const add = _.curry((a, b, c) => a + b + c);
add(1)(2)(3); // 6
add(1, 2)(3); // 6
add(1)(2, 3); // 6
add.length; // 3 (lodash preserves original arity on the curried fn)
// Ramda example
import * as R from "ramda";
const multiply = R.curry((a, b) => a * b);
const double = multiply(2);
[1, 2, 3, 4].map(double); // [2, 4, 6, 8]
Note
fn.length vs manually specified arity: Ramda and lodash both read fn.length. If your function uses default params or rest args, pass the arity explicitly via curryN(n, fn).
Placeholders solve a specific problem: what if you want to apply the 2nd or 3rd argument before the 1st? Without placeholders, you would have to flip argument order or use bind gymnastics.
The _ placeholder concept
Ramda exports a special _ sentinel value. When you pass _ in a position, that slot remains open. On the next call, arguments fill the open slots left to right before filling the remaining positional slots.
example.js
import * as R from "ramda";
const { _, curry } = R;
const f = curry((a, b, c) => `${a}-${b}-${c}`);
// Normal
f("a")("b")("c"); // "a-b-c"
// Apply 2nd arg first, skip 1st
f(_, "b")("a")("c"); // "a-b-c" — _ slot filled with "a" next
// Apply 3rd arg first, skip 1st and 2nd
f(_, _, "c")("a")("b"); // "a-b-c" — _ slots filled L-to-R
// Practical: data-last pattern with placeholder
const getAge = R.prop("age");
const users = [{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }];
users.map(getAge); // [30, 25] — no placeholder needed when data is last
PlaceholderPlaceholder argument: _ marks a slot as open, to be filled on the next call
Placeholder CurryPlaceholder curry: curry(fn)(_, 2)(1) with colour-coded argument slots
Implementing placeholder curry
example.js
const _ = Symbol("placeholder");
function curry(fn, arity = fn.length) {
return function curried(...args) {
// Replace _ with actual values from the next call
function merge(existing, incoming) {
let inIdx = 0;
return existing.map(arg =>
arg === _ && inIdx < incoming.length ? incoming[inIdx++] : arg
).concat(incoming.slice(inIdx));
}
const filled = args;
const openSlots = filled.filter(a => a === _).length;
const totalCollected = filled.length - openSlots;
if (totalCollected >= arity && openSlots === 0) {
// All slots filled — call the original function
return fn.apply(this, filled.slice(0, arity));
}
// Still open slots — return a function that fills them
return function(...more) {
return curried.apply(this, merge(filled, more));
};
};
}
const divide = curry((a, b) => a / b);
const half = divide(_, 2); // _ for numerator, 2 for denominator
half(10); // 5
half(20); // 10
const invert = divide(1); // 1/x
invert(4); // 0.25
Key Insight
Placeholder curry is how Ramda achieves its data-last, point-free style. By putting the data argument last in all functions, every Ramda function becomes composable without needing to explicitly pass data at configuration time.
Compose and pipe are the two fundamental function combination utilities in functional programming. They let you build complex transformations from small, focused functions — no intermediate variables, no nested calls.
compose — right to left
compose(f, g, h)(x) equals f(g(h(x))). The rightmost function runs first. This matches mathematical function composition notation: f ∘ g ∘ h.
example.js
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
const double = x => x * 2;
const addOne = x => x + 1;
const square = x => x * x;
// compose: square runs first, then addOne, then double
const transform = compose(double, addOne, square);
transform(3); // double(addOne(square(3))) = double(addOne(9)) = double(10) = 20
pipe — left to right
pipe(h, g, f)(x) equals f(g(h(x))). The leftmost function runs first. This reads like a pipeline: data flows left to right through each transformation step.
example.js
const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);
// pipe: square runs first, then addOne, then double (same math, more readable order)
const transform = pipe(square, addOne, double);
transform(3); // double(addOne(square(3))) = 20
// Real-world: data processing pipeline
const processUser = pipe(
user => ({ ...user, name: user.name.trim() }), // normalize
user => ({ ...user, email: user.email.toLowerCase() }), // lowercase
user => ({ ...user, age: Number(user.age) }), // coerce
user => ({ ...user, slug: user.name.replace(/ /g, "-") }), // derive
);
processUser({ name: " Alice Smith ", email: "ALICE@EXAMPLE.COM", age: "30" });
// { name: "Alice Smith", email: "alice@example.com", age: 30, slug: "Alice-Smith" }
Compose PipeCompose vs pipe: compose runs right-to-left, pipe runs left-to-right
Compose Vs PipeCompose vs pipe side by side with data blob flowing through function boxes
Compose vs pipe: the array reverse relationship
The key insight: compose(f3, f2, f1)(x) is exactly equivalent topipe(f1, f2, f3)(x). The functions array is just reversed.
example.js
// compose and pipe are the inverse of each other
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);
// Reverse the function array to convert between them
const pipeFromCompose = (...fns) => compose(...fns.reverse());
const composeFromPipe = (...fns) => pipe(...fns.reverse());
// Example
const double = x => x * 2;
const addOne = x => x + 1;
// These are equivalent:
compose(double, addOne)(3); // double(addOne(3)) = 8
pipe(addOne, double)(3); // double(addOne(3)) = 8
composeFromPipe(double, addOne)(3); // = pipe(addOne, double)(3) = 8
// Choose based on readability:
// compose: mathematical notation (innermost first)
// pipe: temporal order (what happens first, listed first)
Tip
Quick rule: if you find yourself squinting at compose trying to figure out which function runs first, swap to pipe and reverse the arguments.compose(f, g, h)(x) === pipe(h, g, f)(x).
Error handling in pipe
In synchronous pipelines, an exception in any step kills the entire pipeline. This is fine for most use cases, but sometimes you want to model failure as data rather than exceptions — especially in async pipelines.
example.js
// A Result type for short-circuit error handling
const Result = {
Ok: val => ({ ok: true, val }),
Err: reason => ({ ok: false, reason }),
// Map: only applies fn if the result is Ok
map: (result, fn) => result.ok ? Result.Ok(fn(result.val)) : result,
// Chain: for fn that returns a Result
chain: (result, fn) => result.ok ? fn(result.val) : result,
};
// Pipe with Result propagation
const pipeResult = (...fns) => x =>
fns.reduce((acc, fn) => Result.map(acc, fn), Result.Ok(x));
// Usage: each step receives Ok(val) or short-circuits on Err
const safeDivide = (denominator) => (numerator) =>
denominator === 0
? Result.Err("Division by zero")
: Result.Ok(numerator / denominator);
const double = x => x * 2;
const negate = x => -x;
const pipeline = pipeResult(
safeDivide(2), // Ok: 10/2 = 5
double, // Ok: 5*2 = 10
negate, // Ok: -10
);
pipeline(10); // { ok: true, val: -10 }
// Short-circuit on error:
const broken = pipeResult(
safeDivide(0), // Err: division by zero — stops here
double, // never runs
);
broken(10); // { ok: false, reason: "Division by zero" }
The Result type makes error handling explicit and composable. Unlike try/catch (which is implicit and easy to forget), Result forces every consumer to handle both the Ok and Err paths. Libraries like Folktale, Sanctuary, and fp-ts provide full implementations of this pattern.
Point-free style — pros & cons
Point-free (also called tacit programming) defines functions without mentioning their arguments. Currying + pipe enables a clean point-free style.
example.js
// Point-full (explicit argument)
const double = x => x * 2;
const numbers = [1, 2, 3];
numbers.map(x => double(x)); // explicit x
// Point-free (argument implicit)
numbers.map(double); // no x mentioned
// With pipe — full point-free pipeline
const isEven = n => n % 2 === 0;
const negate = b => !b;
const isOdd = pipe(isEven, negate); // no argument mentioned!
[1, 2, 3, 4].filter(isOdd); // [1, 3]
// Ramda makes this even cleaner
import * as R from "ramda";
const sumPositives = R.pipe(
R.filter(R.lt(0)), // keep values > 0
R.sum // sum them
);
sumPositives([-1, 2, -3, 4, 5]); // 11
Pros
Readability — pipelines read as a sequence of transformations, no noise from intermediate variables or parameter names.
Reusability — point-free functions are already configured and ready to compose. No lambda wrapping needed.
Testability — each step in a pipe is an independent pure function. Testing the pipeline means testing each function individually.
Parallelism — pure functions in a pipeline can be parallelised (via structured concurrency) with no shared state.
Cons
Debugging — no named intermediate values means you can't inspect the result at step 3 without inserting a tap/log function.
Stack traces — errors in point-free pipelines produce cryptic stack traces (anonymous functions, no variable names).
Over-abstraction — forcing point-free style on complex logic creates unreadable gibberish. Know when to break out.
Arity mismatch — array methods pass index and array as 2nd/3rd args to callbacks. ['1','2'].map(parseInt) returns [1, NaN] because parseInt receives the index as radix.
Tip
Use pipe when you want to read the transformation steps in temporal order (what happens first to last). Use compose when translating math notation directly, or when you're wrapping functions from the outside in (like decorators).
Sync compose and pipe break when any function in the pipeline returns a Promise. The output of step N is a Promise, not the resolved value — and the next function receives a Promise when it expected a plain value.
The problem with sync pipe + async functions
example.js
const fetchUser = async id => { /* returns Promise<User> */ };
const normalizeUser = user => ({ ...user, name: user.name.trim() });
// BROKEN — normalizeUser receives a Promise, not a User
const pipeline = pipe(fetchUser, normalizeUser);
await pipeline(1); // normalizeUser({ then: [Function], ... }) — wrong!
Async pipe implementation
example.js
// asyncPipe: awaits each step before passing to the next
const asyncPipe = (...fns) => x =>
fns.reduce(async (acc, fn) => fn(await acc), x);
// Usage
const processUser = asyncPipe(
fetchUser, // async: id → Promise<User>
normalizeUser, // sync: User → User
async user => { await saveUser(user); return user; }, // async: User → Promise<User>
user => ({ ...user, processed: true }) // sync: User → User
);
await processUser(42); // works correctly — each step awaits the previous
The key is fn(await acc) inside the reduce. Even if acc is a plain value (non-Promise), await is a no-op on non-Promises — so sync functions work too.
Error propagation
example.js
// Errors propagate automatically through async pipe — any rejection short-circuits
const safeProcessUser = asyncPipe(
fetchUser, // throws if user not found → rejects the whole pipeline
validateUser, // throws on invalid data
enrichUser, // adds extra fields
saveUser, // persists
);
try {
await safeProcessUser(99); // if fetchUser throws, validateUser etc. never run
} catch (err) {
console.error("Pipeline failed:", err.message);
}
// For error recovery — wrap individual steps
const withFallback = (fn, fallback) => async x => {
try { return await fn(x); }
catch { return fallback(x); }
};
const resilientPipeline = asyncPipe(
withFallback(fetchUser, () => ({ name: "Guest", id: 0 })), // fallback on fetch error
normalizeUser,
saveUser,
);
Note
Express.js and Koa middleware stacks are async pipes — each middleware calls next() to pass control to the next function. Koa's koa-compose is literally an async pipe over middleware functions. Understanding async pipe makes middleware architectures trivial to reason about.
The data-last convention is why Ramda puts the data argument last in all its functions. When data is last, every function is already configured (via curry) and just waiting for the data to arrive — making pipe compositions effortless. Compare R.map(fn, data) (data-last) to JavaScript's data.map(fn) (data-first — chainable but not pipeable without a wrapper).
Data transformation pipelines
example.js
// ETL pipeline: fetch → normalize → validate → transform → format
const processData = asyncPipe(
fetchRawData,
data => data.map(normalizeKeys),
data => data.filter(validateSchema),
data => data.map(applyBusinessRules),
data => data.map(formatForUI),
);
// Each step is a pure, independently-testable function
// The pipeline composes them without any shared mutable state
10. Real-World Curry Patterns
React event handler pattern
example.js
// Curried event handler — pre-configure field, receive event later
const handleChange = curry((field, e) => {
setState(prev => ({ ...prev, [field]: e.target.value }));
});
// Usage
const Form = () => {
const [form, setForm] = useState({ email: "", name: "" });
// handleChange("email") returns a function that waits for the event
return (
<>
<input name="email" onChange={handleChange("email")} />
<input name="name" onChange={handleChange("name")} />
</>
);
};
// Without curry: inline lambdas everywhere
// <input onChange={e => setForm(prev => ({...prev, email: e.target.value}))} />
// With curry: clean, reusable, composable
The curried handler separates configuration (which field to update) from execution (the event object). This eliminates repetitive inline lambda functions and reduces the chance of stale closures in useEffect deps.
Validation pipeline with pipe
example.js
// Each validator is a pure function: value → error | null
const required = value => !value ? "Required" : null;
const isEmail = value => !/^.+@.+/.test(value) ? "Invalid email" : null;
const minLength = (min) => (value) =>
value.length < min ? `Min ${min} chars` : null;
// Compose validators into a pipeline — first error wins
const validate = (...validators) => (value) => {
for (const fn of validators) {
const error = fn(value);
if (error) return error;
}
return null;
};
// Usage: compose curried validators
const validateEmail = validate(
required,
isEmail,
minLength(5),
);
validateEmail(""); // "Required"
validateEmail("a"); // "Invalid email"
validateEmail("a@b"); // "Min 5 chars"
validateEmail("a@b.co"); // null (valid)
Validation pipelines are a natural fit for currying: each validator is pre-configured (e.g., minLength(5)) and the pipe short-circuits on the first error. The same pattern works for sanitization and transformation chains.
API client factory
example.js
// Curried API client — pre-configure base URL and headers
const createApiClient = curry((baseURL, defaultHeaders, endpoint, body) =>
fetch(`${baseURL}${endpoint}`, {
method: "POST",
headers: { "Content-Type": "application/json", ...defaultHeaders },
body: JSON.stringify(body),
}).then(r => r.json())
);
// Pre-configure the client for a specific service
const api = createApiClient("https://api.example.com");
const authedApi = api({ Authorization: "Bearer tok_123" });
// Now use with just endpoint + body
const login = authedApi("/auth/login");
const signup = authedApi("/auth/signup");
login({ email: "a@b.com", password: "s3cret" });
// = fetch("https://api.example.com/auth/login", { method: "POST", headers: { Authorization: "..." }, body: ... })
Each application of createApiClient "locks in" one layer of configuration: base URL, headers, endpoint, body. The function only executes when all arguments are provided — allowing you to define the shape of your API client once and reuse it with different configurations.
Selector factories (Redux-style)
example.js
// A curried selector factory — pre-configure the field path
const selectField = curry((field, state) => state[field]);
// Create specific selectors without repeating the selection logic
const selectUser = selectField("user");
const selectPosts = selectField("posts");
const selectTheme = selectField("theme");
// compose with data transformations
const selectUserName = pipe(
selectField("user"),
user => user.name,
);
// In Redux / Zustand / Jotai:
const user = useSelector(selectUser);
// More practical: curried reselect-style selector
const createSelector = curry((projectFn, selectors, state) =>
projectFn(...selectors.map(s => s(state)))
);
const getFullName = createSelector(
(first, last) => `${first} ${last}`,
[selectField("firstName"), selectField("lastName")],
);
getFullName({ firstName: "Alice", lastName: "Smith" }); // "Alice Smith"
Selector factories eliminate boilerplate when accessing nested state. The curried selectField is configured once and reused across components — just pass the state object at render time. Combine with pipe for derived data without creating explicit memoised selectors for every combination.
11. Interview Cheat Sheet
Currying appears in nearly every functional-programming interview question and frequently in JavaScript-specific rounds. Here are the 7 most common question types with concise answers.
1What is currying vs partial application?
Currying transforms fn(a,b,c) into fn(a)(b)(c) — one argument per call. Partial application pre-fills any number of arguments at once, returning a function that takes the remaining ones. Both use closures; currying is a stricter subset.
2Implement curry(fn) — the classic
function curry(fn) { return function curried(...args) { if (args.length >= fn.length) return fn.apply(this, args); return (...more) => curried(...args, ...more); }; } — checks collected args against fn.length, recurses until satisfied.
3What is fn.length and when does it not work?
fn.length is the number of declared parameters (not including rest params or parameters after defaults). It breaks for variadic functions (...args → length 0) and functions with default params. Use curryN(n, fn) to pass arity explicitly.
4What is point-free style?
Defining functions without naming their arguments. Enabled by currying + compose/pipe. Example: const isOdd = pipe(isEven, negate) — no x mentioned. Reduces boilerplate but can hurt readability if overused.
5Compose vs pipe — when to use each?
Both produce f(g(h(x))). compose(f,g,h) lists functions in math notation (innermost last). pipe(h,g,f) lists them in execution order (first runs first). Use pipe for readable left-to-right pipelines; use compose when translating math or wrapping from outside-in.
6How do placeholders work in Ramda?
R._ is a sentinel. Passing _ in a position leaves that slot open. The next call fills _ slots left-to-right before filling remaining slots. Allows out-of-order application: curry(f)(_, 2)(1) calls f(1, 2).
7Why put data as the last argument?
Data-last makes curried functions pre-configurable without the data. const double = map(x => x * 2) waits for the array. This composes cleanly in pipe without needing wrapper functions. Ramda follows this convention; native JS Array methods (data.map(fn)) are data-first and require a wrapper.
Key Takeaways
1.Currying transforms fn(a,b,c) into fn(a)(b)(c) — it transforms the function, it does not call it. Every intermediate call is a closure over previously received arguments.
2.fn.length is the key to automatic arity detection. It under-counts with default params and rest params. Use curryN(n, fn) when fn.length is unreliable.
3.The curry implementation is a recursive accumulator: collect args, check against fn.length, call or return a new closure. Grouping (multiple args per call) comes for free.
4.Infinite currying uses an empty-call trigger or valueOf override. The empty-call pattern is explicit and debuggable; valueOf is clever but opaque.
5.Partial application pre-fills N args at once. Currying is a special case of partial application that pre-fills exactly 1 at a time. Both rely on closures.
6.Placeholder currying (Ramda's _) allows out-of-order application. The placeholder is a sentinel; the implementation merges incoming args into open _ slots.
7.compose and pipe both produce f(g(h(x))). The difference is listing order: compose is math notation (innermost last), pipe is temporal order (first listed runs first). Use pipe for readable pipelines.
8.asyncPipe wraps reduce with async/await — fn(await acc). This handles mixed sync/async pipelines and error propagation transparently. It is the pattern behind Express/Koa middleware.