How to toggle a boolean?

Viewed 374811

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;
9 Answers

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)
bool === tool ? bool : tool

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

This is an old question but I think a ES6 update will be good.

Usually we want a toggle that can handle everything without breaking our code.

We can use an initial value for null or undefined values as false.

const boolToggler = b => !(b ?? false)

let foo
console.log('foo:', foo) // undefined

foo = boolToggler(foo)
console.log('foo:', foo) // true (assumes undefined as 'false')

foo = boolToggler(foo)
console.log('foo:', foo); // false

let fee = null
console.log('fee:', fee) // null

fee = boolToggler(fee)
console.log('fee:', fee) // true (assumes null as 'false')

let faa = true
console.log('faa:', faa) // true

faa = boolToggler(faa)
console.log('faa:', faa); // false

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);

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.

Related