Using the NOT Operator (!)
let isToggled = false; isToggled = !isToggled // Output: true
You can use the NOT operator to toggle boolean variables in a single line of code.
Using Conditional (Ternary) Operator
Another approach to toggle a boolean is by using the conditional (ternary) operator. This method allows you to toggle a boolean variable based on a condition.
let isToggled = true; isToggled = isToggled ? false : true; // Output: false
The ternary operator checks the current value of
isToggled and assigns the opposite value accordingly.
Using XOR Operator (^)
let isToggled = true; isToggled = isToggled ^ true; // Output: false
However, this method is less common and might be less intuitive than the previous options.
Using Bitwise NOT (~) Operator
Although not recommended for toggling booleans, you can use the bitwise NOT (~) operator in combination with 1 to toggle a boolean value.
let isToggled = true; isToggled = ~isToggled + 2; // Output: false
This method is less readable and should be avoided for boolean toggling.