Is there a really easy way to toggle a boolean value in javascript?
So far, the best I've got outside of writing a custom function is the ternary:
bool = bool ? false : true;
This question is related to
javascript
boolean
toggle
Let's see this in action:
var b = true;_x000D_
_x000D_
console.log(b); // true_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // false_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // true
_x000D_
Anyways, there is no shorter way than what you currently have.
If you don't mind the boolean being converted to a number (that is either 0 or 1), you can use the Bitwise XOR Assignment Operator. Like so:
bool ^= true; //- toggle value.
This is especially good if you use long, descriptive boolean names, EG:
var inDynamicEditMode = true; // Value is: true (boolean)
inDynamicEditMode ^= true; // Value is: 0 (number)
inDynamicEditMode ^= true; // Value is: 1 (number)
inDynamicEditMode ^= true; // Value is: 0 (number)
This is easier for me to scan than repeating the variable in each line.
This method works in all (major) browsers (and most programming languages).
I was searching after a toggling method that does the same, except for an inital value of null
or undefined
, where it should become false
.
Here it is:
booly = !(booly != false)
bool === tool ? bool : tool
if you want the value to hold true if tool
(another boolean) has the same value
In a case where you may be storing true / false as strings, such as in localStorage where the protocol flipped to multi object storage in 2009 & then flipped back to string only in 2011 - you can use JSON.parse to interpret to boolean on the fly:
this.sidebar = !JSON.parse(this.sidebar);
bool = bool != true;
One of the cases.
Source: Stackoverflow.com