DEV Community

Cover image for 🔥 Inverting Boolean functions in JavaScript
Dom Habersack
Dom Habersack

Posted on • Originally published at islovely.co

9

🔥 Inverting Boolean functions in JavaScript

In JavaScript, we can invert Boolean values with an exclamation mark. That doesn’t work for function names we use as shorthand in array methods like Array.prototype.filter() and Array.prototype.map(). Wrap those in a helper function to have them return the opposite of what they would return normally.

const numbers = [0, 1, 2, 3, 4, 5]
const isEven = n => n % 2 === 0

// the long and short form of this do the same
numbers.filter(number => isEven(number))  // ⇒ [0, 2, 4]
numbers.filter(isEven)                    // ⇒ [0, 2, 4]

// `!` can flip the Boolean value, but it only works with the long form
numbers.filter(number => !isEven(number))  // ⇒ [1, 3, 5]
numbers.filter(!isEven)                    // TypeError (not a function)

// this (curried) helper makes functions return a flipped result
const not = callback => value => !callback(value)

// we can use `not` like this, in both the long and short form
numbers.filter(number => not(isEven)(number))  // ⇒ [1, 3, 5]
numbers.filter(not(isEven))                    // ⇒ [1, 3, 5]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay