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

Handling Variadic Functions

Functions with rest parameters don't curry naturally; decide on fixed arity or use partial application.

Handling Variadic Functions

What you'll learn: Why functions with rest parameters resist currying and how to handle them with fixed arity or partial application.

The Problem with Variadic Functions

You've learned how to curry functions beautifully—but there's a catch. Functions that accept a variable number of arguments (using rest parameters like ...args) don't play nicely with standard currying techniques.

Why? Currying relies on knowing the arity (number of parameters) upfront. When a function can take 2, 5, or 20 arguments, your curry helper doesn't know when to stop collecting arguments and finally execute.

// This variadic function is curry-resistant
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);

// A standard curry helper gets confused:
// When should it stop waiting for more arguments?
// After 1? After 5? It can't tell.

Two Practical Solutions

Option 1: Fix the Arity

Rewrite your function with a fixed number of parameters:

// Fixed-arity version
const add3 = (a, b, c) => a + b + c;
const curriedAdd3 = curry(add3);
curriedAdd3(1)(2)(3); // 6 ✓

Option 2: Use Partial Application

For truly variadic behavior, use partial application instead. Manually decide when to "freeze" some arguments:

const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);

const partialSum = (...fixed) => 
  (...rest) => sum(...fixed, ...rest);

const add10 = partialSum(10);
add10(5, 3, 2); // 20

Key Takeaway: Rest parameters break automatic currying because arity is unknown; choose fixed-parameter versions for currying or embrace partial application for flexibility.