Wizard Wizard - 5 months ago 9
jQuery Question

jquery change global variable inside function

var variable = "before";

change();

alert(variable);

function change(){

variable = "after";

}


Does in possible to change global variable inside function without return ? I need after call function
change
have output "after"

Answer

Yes, it is possible, but remember to NOT put the var keyword in front of it inside the function.

ERORR - DOES NOT WORK:

var variable = "before";

change();

alert(variable);

function change() {

  var variable = "after";

}

WORKS:

var variable = "before";

change();

alert(variable);

function change() {

  variable = "after";

}