Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a boolean back and forth in Javascript

I wonder if it is possible in Javascript to have a click event listener that every time I click changes my boolean from true to false back and forth. Meaning I click one it goes to false, I click again and it goes to true and so on in an infinite loop. I don't even know if it is possible but I tried this:

//This is my listener
circlePicker.click(function () {
    booleanChecker(circlePickerSelector);
    console.log(booleanChecker(circlePickerSelector));
});

//This function checks if the boolean is true or false
function booleanChecker(isThisTrue) {
    // circlePickerSelector = !circlePickerSelector;
    // return circlePickerSelector;
    if (isThisTrue == false) {
        isThisTrue = true;
        console.log("I turned into true");
    } else if (isThisTrue == true) {
        isThisTrue = false;
        console.log("I turned into false");
    }
    return isThisTrue;
}

I would like to know if this is possible. I get a feeling something is wrong in my syntax. Any suggestion is more than welcome.

like image 224
mauricioSanchez Avatar asked Jan 23 '26 02:01

mauricioSanchez


1 Answers

You can toggle it by using the ! operator

circlePicker.click(function () {
    circlePickerSelector = !circlePickerSelector;
    console.log(circlePickerSelector);
});

If circlePickerSelector was originally true, then !circlePickerSelector turns it to false. You can then assign it to the same variable to do the reverse on next click.

like image 74
Joseph Avatar answered Jan 25 '26 14:01

Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!