In JavaScript, partial application can be achieved using techniques like function binding, closures, or the bind
method. Here are a few examples:
Using Function Binding:
function add(a, b) { return a + b; } // Partially applying the add function const add5 = add.bind(null, 5); // Using the partially applied function const result = add5(3); // Result is 8 console.log(result);
Using Closures:
function multiply(a) { return function(b) { return a * b; }; } // Partially applying the multiply function const multiplyBy2 = multiply(2); // Using the partially applied function const result = multiplyBy2(4); // Result is 8 console.log(result);
Using Arrow Functions:
function divide(a, b) { return a / b; } // Partially applying the divide function using arrow function const divideBy2 = (b) => divide(2, b); // Using the partially applied function const result = divideBy2(4); // Result is 2 console.log(result);
All three examples demonstrate partial application by fixing one or more arguments of a function, resulting in a new function with fewer parameters that can be used later. Choose the approach that fits your use case and coding style.