Use this for variables that you need to represent a toggle state
I was working with some events in JavaScript and needed to toggle the state of some canvas objects when pressing a button. I usually see colleagues of mine writing something like:
var toggle = 0;
var chmodButton = document.querySelector("#chmod");
chmodButton.addEventListener("click",function(){
if(toggle == 0){
toggle = 1;
}
else{
toggle = 0;
}
});
which is totally fine. It works. But why not change the function that is called when the event happens into something like this:
chmodButton.addEventListener("click",function(){
toggle = (toggle+1)%2;
)};
It skips the if(...)
part and you have a nice one line of code that changes the variable from 0 to 1 to 0 and so on...
Another way to do it (thanks to @piatra for the suggestion) is to use var toggle = true
instead of var toggle = 0
and change the code inside the event function to :
chmodButton.addEventListener("click",function(){
toggle = !toggle;
)};
Also as a side note, this isn't specifically for JavaScript, I just wrote it here like this :)
Written by Bogdan Cernat
Related protips
5 Responses
toggle = !toggle;
@piatra Sure, this is a nice way to do it too :D
Also, toggle = 1 - toggle;
@twolfson Ha! nice! didn't think of this.
...and toggle = toggle ^ 1
(xor 1) which can be rewritten as
toggle ^= 1;