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"
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"
Yes, it is possible, but remember to NOT put the var
keyword in front of it inside the function.
var variable = "before";
change();
alert(variable);
function change() {
var variable = "after";
}
var variable = "before";
change();
alert(variable);
function change() {
variable = "after";
}
You should avoid declaring global variables since they add themselves as properties to the window
. However, to answer your question, yes you can change global variables by setting either changing variable
or window.variable
.
Example: http://jsbin.com/xujenimiwe/3/edit?js,console,output
var variable = "before"; // will add property to window -- window.variable
console.log(variable);
change();
console.log(window.variable);
function change(){
variable = "after"; // can also use window.variable = "after"
}
Please let me know if you have any questions!