Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle boolean using function? [duplicate]

Tags:

javascript

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 ?


1 Answers

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;
like image 114
Tushar Avatar answered Apr 23 '26 20:04

Tushar