Code Snippets
/

Curry a Function in JavaScript

Curry a Function in JavaScript

Currying turns a multi-argument function into a chain of single-argument calls so you can pre-bind some arguments and pass the rest later. This snippet covers the variadic curry every codebase reaches for, a placeholder-aware version for skipping argument positions, and a typed-friendly fixed-arity helper for stricter call shapes. Use it for partial application and to build small DSLs.

JavaScript
Medium
3 snippets
utility
code-template
currying
functional-programming

699 views

3

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

const add3 = curry((a, b, c) => a + b + c);
console.log(add3(1, 2, 3)); // 6
console.log(add3(1)(2)(3)); // 6
console.log(add3(1, 2)(3)); // 6
console.log(add3(1)(2, 3)); // 6

The classic implementation reads fn.length (the declared parameter count) and keeps collecting arguments until at least that many have been supplied. As long as fewer arguments arrive, it returns a fresh function that prepends the captured args to the next batch. Using fn.apply(this, args) keeps the original this binding, which matters when the curried target is a method. The base case is one line; the recursive case is one line. Use this version whenever you want partial application that supports both f(1, 2) and f(1)(2) call shapes.