Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boolean does not change its 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?

like image 411
brigysl Avatar asked Dec 24 '22 02:12

brigysl


1 Answers

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.

like image 50
David Avatar answered Jan 07 '23 18:01

David