Partial application in Javascript

In JavaScript, partial application involves creating a new function by fixing some of the arguments of an existing function.

Hieu Tran Duc

In JavaScript, partial application can be achieved using techniques like function binding, closures, or the bind method. Here are a few examples:

  1. 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);
  2. 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);
  3. 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.

Techgoda

We are a community of developers who are passionate about technology and programming.

Check out Techgoda code