How to Toggle a Boolean in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 13, 2021

banner

Photo from Unsplash

Toggle a Boolean in JavaScript #

Use the logical NOT (!) operator to toggle a boolean in JavaScript, e.g. bool = !bool. When used with a boolean value, the logical NOT (!) operator will toggle the value of the boolean and return the result.

index.js
let bool = true; bool = !bool; console.log(bool); // 👉️ false

We used the logical NOT (!) operator to toggle a boolean value.

When used with a value of true, the operator returns false and vice versa.

index.js
console.log(!true); // false console.log(!false); // true

Here are some more examples of using the logical NOT (!) operator.

index.js
console.log(!'my str'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true console.log(!undefined); // 👉️ true

The operator converts the value to a boolean (if it isn't one already), flips the boolean and returns the result.

Notice that we used the let keyword to declare the bool variable. Had we used const, we would not be able to reassign it.

An alternative approach is to use the strict inequality (!==) operator.

To toggle a boolean, use the strict inequality (!==) operator to compare the boolean to true, e.g. bool !== true. The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

index.js
let bool = true; bool = bool !== true; console.log(bool); // 👉️ false bool = bool !== true; console.log(bool); // 👉️ true

The first example conditionally checks if a value of true is not equal to true. The comparison evaluates to false, effectively flipping the boolean.

The second checks if false is not equal to true, which evaluates to true and toggles the boolean again.

My personal preference is to use the logical NOT (!) operator approach. I find it more intuitive, direct, and easier to read than using the strict inequality (!==) operator.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.