# Currying and Function Composition

> What is currying in JavaScript, how is it different from partial application, and how do you combine small functions using compose and pipe?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-currying-composition
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What is currying in JavaScript, how is it different from partial application, and how do you combine small functions using compose and pipe?

## Answer

Currying transforms a function that takes several arguments, `f(a, b, c)`, into a chain of functions that each take one argument, `f(a)(b)(c)`. Partial application is related but different: it fixes some arguments of a function and returns a function that takes the rest, in whatever grouping. Function composition builds a new function by feeding the output of one function into the next, usually with `pipe` (left to right) or `compose` (right to left).

### Currying vs partial application

| Aspect | Currying | Partial application |
| --- | --- | --- |
| Shape | Always unary steps: `f(a)(b)(c)` | Fix any number now, rest later: `g(c)` |
| Result | Sequence of single-argument functions | One function with fewer parameters |
| Built-in support | None, write a helper | `fn.bind(null, a, b)` |
| Typical helper | `curry(fn)` using `fn.length` | `partial(fn, ...fixed)` |

In practice, most "curry" helpers in libraries like Lodash and Ramda are auto-curried: they accept arguments one at a time or several at once (`add(1)(2)(3)`, `add(1, 2)(3)`), so they blur the two ideas. Strictly speaking, that is a mix of currying and partial application.

### How a generic curry helper works

A curry helper uses `fn.length`, the number of declared parameters, as the target arity:

1. Collect the arguments received so far.
2. If enough arguments have arrived, call the original function.
3. Otherwise return a new function that collects more and repeats.

Note that `fn.length` does not count rest parameters or parameters after the first one with a default value, so `curry` does not work on `(...args) => {}` or `(a, b = 1) => {}` unless you pass the arity explicitly.

### Why currying and composition are useful

- **Reusable specialised functions**: `const withGst = addTax(0.18)` creates a GST calculator you can pass to `map`.
- **Point-free pipelines**: `pipe(trim, toLowerCase, slugify)` reads like a recipe and each step is easy to unit test.
- **Configuration first, data last**: functions like `filterBy('city')('Pune')` fit naturally into `array.filter`.
- **Real-world examples**: Redux middleware has the curried signature `store => next => action => {}`, and Redux's `compose` combines store enhancers. Event handler factories in React (`handleChange = field => e => ...`) are curried functions too.

### compose vs pipe

Both are one-liners with `reduce`:

- `compose(f, g, h)(x)` equals `f(g(h(x)))`, mathematical order, right to left.
- `pipe(f, g, h)(x)` equals `h(g(f(x)))`, reading order, left to right.

Each function in the chain should take a single argument (which is where currying helps) and return the value the next one expects. There is a TC39 pipeline operator proposal (`|>`), but it is still Stage 2 and not usable without a transpiler.

### Trade-offs and gotchas

- Deeply curried code can be hard to read for teammates who are not used to functional style. Use it where it simplifies, not everywhere.
- Each curried call allocates a closure; in hot loops this has a small cost.
- Argument order matters: put the parameter most likely to change (usually the data) last.
- Debugging long point-free pipelines is harder; a `tap(console.log)` helper in the pipe makes it easier.

**pipe(f1, f2, f3)(5). Reorder or rewrite the functions under Tweak: composition order changes the result.**

1. **f1 = x + 1**: 5 → 6
2. **f2 = x \* 2**: 6 → 12
3. **f3 = x \* x**: 12 → 144
4. **pipe vs compose**: pipe applies left to right; compose applies right to left.

## Code examples

### Generic curry helper and partial application

```
function curry(fn, arity = fn.length) {
  return function curried(...args) {
    if (args.length >= arity) return fn.apply(this, args);
    return (...more) => curried.apply(this, [...args, ...more]);
  };
}

const priceWithTax = (rate, discount, price) =>
  Math.round((price - discount) * (1 + rate));

const curried = curry(priceWithTax);
const withGst = curried(0.18);       // fix the tax rate
const withGstNoDiscount = withGst(0); // fix the discount

console.log(curried(0.18)(0)(1000));
console.log(curried(0.18, 100)(1000)); // auto-curried: several at once
console.log([200, 500].map(withGstNoDiscount));

// Partial application with bind: fix the first two args at once
const festiveSale = priceWithTax.bind(null, 0.18, 200);
console.log(festiveSale(1000));
```

The curry helper keeps collecting arguments until it has as many as fn.length, then calls the original. bind performs partial application directly, fixing two arguments in one step.

### pipe and compose

```
const pipe = (...fns) => input => fns.reduce((acc, fn) => fn(acc), input);
const compose = (...fns) => input => fns.reduceRight((acc, fn) => fn(acc), input);

const trim = s => s.trim();
const lower = s => s.toLowerCase();
const slugify = s => s.replace(/\s+/g, '-');
const tap = label => v => (console.log(label, v), v);

const toSlug = pipe(trim, lower, tap('after lower:'), slugify);
console.log(toSlug('  Masala Dosa Combo '));

const toSlug2 = compose(slugify, lower, trim); // same result, reversed order
console.log(toSlug2('  Paneer Tikka  '));
```

pipe applies functions left to right and compose right to left; both are a single reduce. A tap helper lets you log intermediate values without breaking the chain.

## Key points

- Currying turns f(a, b, c) into f(a)(b)(c); partial application fixes some arguments and returns a function for the rest.
- Function.prototype.bind is built-in partial application.
- Curry helpers rely on fn.length, which ignores rest parameters and parameters from the first default onward.
- pipe runs left to right, compose runs right to left; both are a reduce over functions.
- Redux middleware (store => next => action) is a well-known curried signature.

## Common follow-up questions

- Implement a curry function that supports placeholders.
- Write an infinite curry sum such that sum(1)(2)(3)() returns 6.
- How does Redux's applyMiddleware use compose?
- When would currying make code harder to maintain?
- What is point-free style?

## Interview tips

- Clearly separate currying from partial application; mixing them up is the most common mistake.
- Be ready to write curry from scratch, including the fn.length check and the recursive return.
- Ground the answer in a real example such as Redux middleware or event handler factories.

## Concepts covered

Currying, Partial Application, Function Composition, pipe, compose, Arity

Previous: [Optional Chaining and Nullish Coalescing](https://www.internhack.in/learn/interview/javascript-interview/js-optional-chaining-nullish) · Next: [Memoization](https://www.internhack.in/learn/interview/javascript-interview/js-memoization) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Property Descriptors and Object.defineProperty](https://www.internhack.in/learn/interview/javascript-interview/js-property-descriptors)
- [Deep Cloning: structuredClone vs JSON](https://www.internhack.in/learn/interview/javascript-interview/js-structuredclone)
- [JavaScript Design Patterns](https://www.internhack.in/learn/interview/javascript-interview/js-design-patterns)
- [Memory Leaks in JavaScript](https://www.internhack.in/learn/interview/javascript-interview/js-memory-leaks)
- [Custom Error Types and Error Handling](https://www.internhack.in/learn/interview/javascript-interview/js-error-types)
- [WebSockets and Real-time Communication](https://www.internhack.in/learn/interview/javascript-interview/js-websockets)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
