2
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"

Alexander Arutinyants
  • 1,619
  • 2
  • 23
  • 49
Wizard
  • 10,985
  • 38
  • 91
  • 165
  • It is possible, but why would you use globals to begin with? Why can't the function take one argument? – elclanrs Dec 25 '14 at 21:49
  • I want set variable globally from ajax response – Wizard Dec 25 '14 at 21:50
  • You may want to check [this question](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call), because that's seems like a pretty common mistake. – elclanrs Dec 25 '14 at 21:51
  • Yes you need not return the variable. The callback would change its value. – Shrutee Dec 25 '14 at 21:53
  • 2
    Short answer is yes. Long answer is you should read [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Variable_scope), and [this](http://stackoverflow.com/a/500459/2782135), to get to know all you need about scopes in JavaScript. – Alexander Arutinyants Dec 25 '14 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 Dec 25 '14 at 22:00

2 Answers2

9

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";

}
Ian Hazzard
  • 7,661
  • 7
  • 34
  • 60
2

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!

Dom
  • 38,906
  • 12
  • 52
  • 81
  • Can you please explain why this does not work? https://jsfiddle.net/y6etz8w3/1/ I already tried setting window.selectedElement as well – Lucas Bustamante Jun 16 '17 at 19:59