how to use the negate function from the underscore library in javascript

The negate function in the underscore library is a high-order function that returns a new function which is the negation of the original function. This function can be used to reverse a boolean test or to compose complex functions.

To use the negate function from underscore, first, you need to import the _ library (assuming it has been installed as a dependency in your project):

index.tsx
const _ = require('underscore');
33 chars
2 lines

Then, you can use it like this:

index.tsx
const isEven = n => n % 2 === 0;
const isOdd = _.negate(isEven);

console.log(isEven(4)); // true
console.log(isOdd(4)); // false
console.log(isEven(5)); // false
console.log(isOdd(5)); // true
194 chars
8 lines

Here, we define two functions isEven and isOdd, the latter being the negation of the former using _.negate. We can then test them on different values to check if they work.

In the above example, we have used the negate function to reverse a boolean test, i.e., to create an odd number testing function by negating an even number testing function.

Happy coding!

gistlibby LogSnag