So far I am trying with:
var myBoolean = false; // global
function toggleBoolean(vr) {
vr = !vr;
}
alert(myBoolean); // false
toggleBoolean(myBoolean);
alert(myBoolean); // false
But obviously, It failed.
Edit: sorry, I forgot to point out that I want the function to work with many Booleans and not just one
So far I am trying with:
var myBoolean = false; // global
function toggleBoolean(vr) {
vr = !vr;
}
alert(myBoolean); // false
toggleBoolean(myBoolean);
alert(myBoolean); // false
But obviously, It failed.
Edit: sorry, I forgot to point out that I want the function to work with many Booleans and not just one
Share Improve this question edited Dec 16, 2011 at 1:02 Jan Pöschko 5,5801 gold badge30 silver badges28 bronze badges asked Dec 15, 2011 at 23:55 user1022373user10223733 Answers
Reset to default 5Yes, you can toggle a global boolean from a function. You can't do it as in your attempt because JavaScript is strictly call-by-value.
function toggleBoolean() {
myBoolean = ! myBoolean;
}
Now, if you want to toggle a global by name, you could do this (though it's a little icky):
function toggleBoolean(name) {
window[ name ] = ! window[ name ];
}
Global variables (in JavaScript on a browser) are properties of the global object, which is known as "window". In other contexts there are ways of associating a name with the global context. You'd call that function, therefore, like this:
toggleBoolean( "myBoolean" );
Note that I pass a string there instead of a reference to the actual global variable.
you are passing the value to the function by value. Instead, to achieve what you want, you can do something like:
var myBoolean=false;// Global
function toggleBoolean(){
myBoolean = !myBoolean;
}
You can do
var myState = { state : false };
function toggleBoolean( s )
{
s.state = ! s.state;
}
alert( myState.state );
toggleBoolean( myState );
alert( myState.state );
primitives are passed by value by default in javascript. You can have a wrapper object and pass the object to the toggle function.