Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for flipping a boolean variable

How can I flip the value of a boolean variable in javascript, without having to include the variable name twice? So

foobarthings[foothing][barthing] = !foobarthings[foothing][barthing]; 

without writing foobarthings[foothing][barthing] twice.

like image 659
chtenb Avatar asked Dec 20 '12 13:12

chtenb


People also ask

How do you flip a Boolean value?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

How do you make a boolean opposite?

The operator. not_() function takes a boolean value as its argument and returns the opposite of that value.

How do you invert a boolean in JavaScript?

Method 1: Using the logical NOT operator: The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can be used to toggle a boolean value.

How do you write a boolean variable?

To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”.


2 Answers

There is no shorter way than what you currently have.

like image 99
alex Avatar answered Sep 21 '22 03:09

alex


You can do this:

foo ^= 1 

But this really switches foo between 0 and 1, not true and false.

like image 38
Sjoerd Avatar answered Sep 21 '22 03:09

Sjoerd