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"
- It is possible, but why would you use globals to begin with? Why can't the function take one argument? – elclanrs Commented Dec 25, 2014 at 21:49
- I want set variable globally from ajax response – Wizard Commented Dec 25, 2014 at 21:50
- You may want to check this question, because that's seems like a pretty mon mistake. – elclanrs Commented Dec 25, 2014 at 21:51
- 2 Short answer is yes. Long answer is you should read this, and this, to get to know all you need about scopes in JavaScript. – Alexander Art Commented Dec 25, 2014 at 21:54
- 2 If it's ajax, you should say so in the question, as Asynchronous Javascript And XML is ... wait for it... asynchronous, and setting global variables is not the solution, as others above have noted. – adeneo Commented Dec 25, 2014 at 22:00
2 Answers
Reset to default 9Yes, 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";
}
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./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!