Boolean does not change its value

I am stuck in this code and don’t understand why it does not work as I expect. Thus, the boolean variable "x" changes its value each time I press the button #btn:

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

But in this way, "x" does not change its meaning:

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

Why is this?

+4
source share
2 answers

Since you have two variables x.

One thing announced:

var x = false;

Another is announced here:

function toggleBtn(x) {

In the first example, you update the value of the first x. In the second example, you update the value of the second x. Which then immediately leaves the scope when the function ends and is destroyed.

+8
source

Try:

$(document).ready(function(){

     var x = false;

    $("#btn").click(function() {
        toggleBtn(x);
    })

    function toggleBtn(x) {
        if (!x)
            doThis();

        else 
            doThat();         
    }

    function doThis() {
        alert("do This");
        x = !x;
    }

    function doThat() {
        alert("do That");
        x = !x;
    }

}) 

:

<!DOCTYPE html>
<html>
<head>
    <style>
    </style>
</head>
<body>
    <button id="btn">OK</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        
$(document).ready(function(){
    
     var x = false;
    
    $("#btn").click(function() {
        
        toggleBtn(x);
        
    })
    
    function toggleBtn(x) {
        
        if (!x)
            doThis();
        
        else 
            doThat();
                
    }
    
    function doThis() {
        alert("do This");
        x = !x;
    }
    
    function doThat() {
        alert("do That");
        x = !x;
    }
})
        
    </script>
</body>
</html>
Hide result
+2

Source: https://habr.com/ru/post/1653467/


All Articles