brigysl brigysl - 3 months ago 8
jQuery Question

boolean does not change it's value

I'm stuck with this code and do not understand why it's not working as I expect. This way, the boolean variable "x" changes its value every time I click the

#btn
:

$(document).ready(function() {
var x = false;
$("#btn").click(function() {
toggleBtn(x);
x = !x;
});
function toggleBtn(x) {
if (!x) {
doThis();
} else {
doThat();
}
};
});


But this way, "x" does not change it's value:

$(document).ready(function() {
var x = false;
$("#btn").click(function() {
toggleBtn(x);
});
function toggleBtn(x) {
if (!x) {
doThis();
} else {
doThat();
}
x = !x;
};
});


Why is that?

Answer

Because you have two x variables.

One is declared here:

var x = false;

The other is declared here:

function toggleBtn(x) {

In the first example, you're updating the value of the first x. In the second example, you're updating the value of the second x. Which then immediately falls out of scope when the function ends and is destroyed.

Comments