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

Implementing Partial Application

Use Function.prototype.bind or write a custom partial function to preset some arguments.

Implementing Partial Application

You'll learn how to preset function arguments using Function.prototype.bind or a custom helper function.

Partial application means taking a function and fixing some of its arguments upfront, returning a new function that waits for the remaining arguments. It's like preparing a sandwich assembly line: you pre-set the bread and condiments, then only add the filling later.

Using Function.prototype.bind

The built-in bind method can perform partial application. Its first argument sets this (use null if you don't care), and subsequent arguments become preset parameters:

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

const multiplyBy2 = multiply.bind(null, 2);
console.log(multiplyBy2(3, 4)); // 2 * 3 * 4 = 24

const multiplyBy2And3 = multiply.bind(null, 2, 3);
console.log(multiplyBy2And3(4)); // 2 * 3 * 4 = 24

Writing a Custom Partial Function

For more flexibility, create a partial helper that doesn't involve this:

function partial(fn, ...fixedArgs) {
  return function(...remainingArgs) {
    return fn(...fixedArgs, ...remainingArgs);
  };
}

function greet(greeting, name, punctuation) {
  return greeting + ' ' + name + punctuation;
}

const sayHello = partial(greet, 'Hello');
console.log(sayHello('Alice', '!')); // "Hello Alice!"

const sayHelloAlice = partial(greet, 'Hello', 'Alice');
console.log(sayHelloAlice('!!!')); // "Hello Alice!!!"

The partial function captures the preset arguments in a closure, then combines them with whatever arguments you provide later.

Key Takeaway: Partial application lets you preset function arguments using bind(null, arg1, arg2) or a custom partial helper, creating specialized functions from general-purpose ones without calling the original function immediately.