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>