Course contentsShow
← JavaScript
Lesson 513 of 2,72313. ClosuresFree lesson

Partial Application via Closures

Fix some arguments of a function and return a new function that remembers those values.

Partial Application via Closures

What you'll learn: How to "pre-fill" some arguments of a function using closures, creating specialized versions that remember those fixed values.

The Core Idea

Partial application means taking a function that accepts multiple parameters and "locking in" some of those parameters ahead of time. You return a new function that remembers the fixed values and only asks for the remaining arguments. Closures make this possible—the inner function captures the pre-set values in its scope.

Think of it like a form with some fields already filled out. Instead of asking for all information every time, you create a customized form that only asks for what's left.

How It Works

function multiply(a, b) {
  return a * b;
}

// Create a partial application
function multiplyByTen(b) {
  return multiply(10, b);  // 'a' is fixed at 10
}

console.log(multiplyByTen(5));  // 50

You can make this more generic with a helper:

function partial(fn, fixedArg) {
  return function(remainingArg) {
    return fn(fixedArg, remainingArg);
  };
}

const double = partial(multiply, 2);
const triple = partial(multiply, 3);

console.log(double(7));   // 14
console.log(triple(7));   // 21

The returned function closes over fn and fixedArg, so it "remembers" them even after partial finishes executing.

Practical Use

function greet(greeting, name) {
  return `${greeting}, ${name}!`;
}

const sayHello = partial(greet, "Hello");
const sayGoodbye = partial(greet, "Goodbye");

console.log(sayHello("Alice"));     // "Hello, Alice!"
console.log(sayGoodbye("Bob"));     // "Goodbye, Bob!"

Key Takeaway: Partial application uses closures to create specialized versions of functions by fixing some arguments upfront, letting you build reusable, focused functions from more general ones.