3

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 ?

  • 3
    inside of `function toggle(x)` you're setting the local variable `x` to `!x` (and this local variable is gone after the method ends). Booleans, in most languages, are simple types, not objects or references – Don Cheadle Jun 07 '16 at 15:49
  • 2
    You realise anywhere in code where you called `toggle(x)` would be shorter to just write `!x` - which does the job of negating a boolean – Jamiec Jun 07 '16 at 15:51

1 Answers1

10

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;
Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • *All* types are passed by value in JavaScript. The value, when referring to objects, is an object reference, but it's still passed by value. – T.J. Crowder Jun 07 '16 at 15:51