How to Toggle a Boolean in JavaScript


Borislav Hadzhiev

Sat Nov 13 20212 min read

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.

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.

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

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

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.

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee