Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

Explain the concept of partial application

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

Partial application is a technique in functional programming where a function is applied to some of its arguments, producing a new function that takes the remaining arguments. This allows you to create more specific functions from general ones. For example, if you have a function add(a, b), you can partially apply it to create a new function add5 that always adds 5 to its argument.

function add(a, b) {
return a + b;
}
const add5 = add.bind(null, 5);
console.log(add5(10)); // Outputs 15

Partial application

Partial application is a functional programming technique where a function is applied to some of its arguments, producing a new function that takes the remaining arguments. This can be useful for creating more specific functions from general ones, improving code reusability and readability.

Example

Consider a simple add function that takes two arguments:

function add(a, b) {
return a + b;
}

Using partial application, you can create a new function add5 that always adds 5 to its argument:

const add5 = add.bind(null, 5);
console.log(add5(10)); // Outputs 15

How it works

In the example above, add.bind(null, 5) creates a new function where the first argument (a) is fixed to 5. The null value is used as the this context, which is not relevant in this case.

Benefits

  • Code reusability: You can create more specific functions from general ones, making your code more modular and reusable.
  • Readability: Partially applied functions can make your code easier to read and understand by reducing the number of arguments you need to pass around.

Real-world example

Partial application is often used in libraries like Lodash. For example, Lodash's _.partial function allows you to create partially applied functions easily:

const _ = require('lodash');
function greet(greeting, name) {
return `${greeting}, ${name}!`;
}
const sayHelloTo = _.partial(greet, 'Hello');
console.log(sayHelloTo('John')); // Outputs "Hello, John!"

Further reading

Edit on GitHub