How to use the partial function from underscore

Find comprehensive JavaScript underscore.partial code examples handpicked from public code repositorys.

underscore.partial is a function in the Underscore.js library that returns a new function with pre-filled arguments for a given function.

5567
5568
5569
5570
5571
5572
5573
5574
5575
5576

// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
  return _.partial(wrapper, func);
};

// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
fork icon0
star icon2
watch icon0

How does underscore.partial work?

_.partial is an Underscore.js function that allows you to partially apply a function, which means that you can create a new function with some of the arguments of the original function pre-set. When you call the new function, you only need to supply the remaining arguments.

Ai Example

1
2
3
4
5
6
7
8
9
const greeting = function (greetingType, name) {
  return `${greetingType} ${name}!`;
};

const sayHello = _.partial(greeting, "Hello");
const sayGoodbye = _.partial(greeting, "Goodbye");

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

In this example, _.partial is used to create two new functions sayHello and sayGoodbye with the first argument to the greeting function partially applied. When these new functions are called, the partially applied argument is already set, and the second argument is supplied when calling the new functions.