Last Updated: September 09, 2019
·
1.578K
· bogdancernat

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

5 Responses
Add your response

toggle = !toggle;

over 1 year ago ·

@piatra Sure, this is a nice way to do it too :D

over 1 year ago ·

Also, toggle = 1 - toggle;

over 1 year ago ·

@twolfson Ha! nice! didn't think of this.

over 1 year ago ·

...and toggle = toggle ^ 1 (xor 1) which can be rewritten as

toggle ^= 1;
over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside