Fernando Souza Fernando Souza - 1 month ago 6
Javascript Question

Changing a global variable

I need your help: I have a variable anima, so when myFunction1() is execulted, it will be set to another value. So when I execute myFunction2(), switch case will work accourding to the value that was set on myFunction1(), and than set anima to another value again.

var anima= 1;

function myFunction1(){

switch(anima) {
case 1:
alert("initial value");
break;
case 2:
alert(anima);
break;
case 3:
anime4r();
break;
case 4:
anime5r();
}
var anima= 2;

}

function myFunction2(){

switch(anima) {
case 1:
anime1();
break;
case 2:
alert("it worked");
break;
case 3:
anime4r();
break;
case 4:
anime5r();
}
var anima= 1;

}

Answer

Get rid of the var in var anima= 2; and var anima= 1; (in function myFunction2()). You are redefining the variable in a local scope so the change is not to the global variable.

Comments