-1

I'm trying to create a button that when it clicked it can change the variable that I already declared

here is my simple code but it doesn't seem to work

<script>
var a = 1;
function myFunction(a){
  if(a=1){
    alert("the value of a now is" + a);
    a=2
  }else if(a=2){
    alert("the value of a now is" + a);
  }      
}
</script>

what I expected to work is that if I run or click the button twice the result will be it alerting me that "the value of a now is 2" but it keeps alerting me "the value of a now is 1"

  • `myFunction` has a parameter called `a` which shadows the global variable. – Titus Aug 06 '19 at 16:14
  • `a=1` is an assignment (and it resolves to `1`, *truthy*). `a==1` or better `a===1` are comparisons. And yes, assigning a value inside a condition makes is valid JS – Thomas Aug 06 '19 at 16:42

2 Answers2

1

You are doing an assignment operation = in the if() and else if() block do a comparison check using the equality == operator:

 if(a == 1)

And in the else if:

else if(a == 2)

This is why you always get the output:

"the value of a now is 1"

As the value of 1 is repeatedly assigned to a when you invoke the function.

Also you would lose access to the local variable a inside the function after you assign in the if block to the value 2, later when you execute the function again you would check the new local variable.

In order to prevent this do not use a local variable in the function parameter, just access the global a.

var a = 1;
function myFunction(){
  if(a == 1){
    alert("the value of a now is" + a);
    a = 2;
  }else if(a == 2){
    alert("the value of a now is" + a);
  }      
}

You can also use the module pattern to prevent the pollution of the global namespace with unnecessary variables.

var handler = (function myFunction(){
  var a = 1;
  return function(){
    if(a == 1){
      alert("the value of a now is" + a);
      a = 2;
    }else if(a == 2){
      alert("the value of a now is" + a);
    }
  };
})();
<button onclick="handler()" id="myButton">Click</button>
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
0

When you use a as a function parameter, you access a local variable a rather than your global a.

Do one of the following:

var a = 1;

// myFunction uses global 'a'
function myFunction(){
  if(a=1){
    alert("the value of a now is" + a);
    a=2
  }else if(a=2){
    alert("the value of a now is" + a);
  }      
}
var a = 1;

// myFunction takes a variable
function myFunction(a){
  if(a=1){
    alert("the value of a now is" + a);
    a=2
  }else if(a=2){
    alert("the value of a now is" + a);
  }      
}

// myFunction is passed global 'a'
myFunction(a);
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25