Last updated: Mar 4, 2024
Reading timeยท3 min
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 logical NOT (!) operator:
let
keyword to declare the bool
variable.let bool = true; bool = !bool; console.log(bool); // ๐๏ธ false
Variables declared using const
cannot be reassigned.
An alternative approach is to use the strict inequality (!==) operator.
To toggle a boolean:
true
.false
if the boolean is equal to true
and vice
versa.let bool = true; bool = bool !== true; console.log(bool); // ๐๏ธ false bool = bool !== true; console.log(bool); // ๐๏ธ true
The first comparison checks if a value of true
is not equal to true
.
The comparison evaluates to false
, effectively toggling the boolean.
The second comparison checks if false
is not equal to true
, which evaluates
to true
and toggles the boolean again.
You can also use the ternary operator to toggle a boolean.
let bool = true; bool = bool === true ? false : true; console.log(bool); // ๐๏ธ false
The ternary operator is
very similar to an if/else
statement.
If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.
You can imagine that the value before the colon is the if
block and the value
after the colon is the else
block.
If the bool
variable stores a true
value, the value before the colon
(false
) is returned, otherwise, the value after the colon (true
) is
returned.
You can also use the Bitwise XOR (^) operator to toggle a boolean and convert it to its integer equivalent.
let bool = true; bool ^= true; console.log(bool); // ๐๏ธ 0 bool ^= true; console.log(bool); // ๐๏ธ 1
The
bitwise XOR (^)
operator will return 0
if the boolean is true
and 1
if the boolean is
false
.
if
statementYou can also use a simple if
statement to toggle a boolean value.
let bool = true; if (bool === true) { bool = false; } else { bool = true; } console.log(bool);
We check if the bool
variable stores a true
value and if it does, we
reassign the variable setting it to false
.
Otherwise, we set the variable to true
just to be sure the variable stores a
boolean.
You can learn more about the related topics by checking out the following tutorials: