I would like to create a single function to toggle any boolean of my code, but I'm not able to get the expected result :
function toggle(x){
x=!x;
}
var test=false;
toggle(test);
alert(test);
Why doesn't this return true ?
Boolean datatype is passed by value. So, any changes made to the argument x will not reflect the actual variable test. You need to return the updated value from the function and assign it back to the variable.
function toggle(x) {
return !x; // Return negated value
}
var test = false;
test = toggle(test); // Assign the updated value back to the variable
alert(test);
But, as said in comments, it's better to use
test = !test;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With