There is no shorter way than what you currently have.
Shorthand for flipping a boolean variable
-
11-12-2021 - |
Question
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.
La solution
Autres conseils
You can do this:
foo ^= 1
But this really switches foo between 0 and 1, not true and false.
var value = true;
alert(value);
value ^= true;
alert(value);
You could get 1 or 0 here
To flip the value of a boolean variable in JS you need the syntax like this:
return !foo;
It's really that easy...
Or you can do (foo ^= 1) == true
(must be == not ===)
You can have just foo and !foo in the place where you execute it or check the condition.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow