510

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;
Flip
  • 5,443
  • 6
  • 39
  • 69
Chris Dutrow
  • 45,764
  • 62
  • 180
  • 249

8 Answers8

1136
bool = !bool;

This holds true in most languages.

Jordan
  • 30,837
  • 6
  • 53
  • 65
116

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:
let 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).

NearHuscarl
  • 38,825
  • 11
  • 144
  • 140
Brock Adams
  • 86,878
  • 22
  • 220
  • 282
14
bool = bool != true;

One of the cases.

Feeco
  • 4,518
  • 7
  • 29
  • 64
11

Let's see this in action:

var b = true;

console.log(b); // true

b = !b;
console.log(b); // false

b = !b;
console.log(b); // true

Anyways, there is no shorter way than what you currently have.

xameeramir
  • 25,752
  • 22
  • 132
  • 205
3

I was searching after a toggling method that does the same, but which "toggles" an initial value of null or undefined to false.

Here it is:

booly = !(booly != false)
OfirD
  • 7,020
  • 2
  • 33
  • 68
1
bool === tool ? bool : tool

if you want the value to hold true if tool (another boolean) has the same value

Ardhi
  • 2,535
  • 20
  • 28
0

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);
Grant
  • 4,655
  • 1
  • 32
  • 43
  • In case the variable has a different values for true/false like "Yes"/"No", I use `sidebar = (sidebar == trueValue) falseValue : trueValue;` – alans Feb 08 '21 at 22:29
0

I always liked Boolean value, but nowadays I'm using binary for both convenience and debugging. You can use de consept !key : ++key: --key to toggle, and if you are in any asynchronous function or anytime an error or false true occurs, the value will leak out of 0(zero)/ 1(one) and you can trigger an alert to debug later.

Rafael Lucas
  • 105
  • 6