174

I am using JavaScript and I create a global variable. I define it outside of a function and I want to change the global variable value from inside a function and use it from another function, how do I do this?

Necreaux
  • 9,451
  • 7
  • 26
  • 43
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143

6 Answers6

187

Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.

You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.

That's why it's considered best practice to always declare your variables explicitly with var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.

Spudley
  • 166,037
  • 39
  • 233
  • 307
  • 3
    This doesn't work for me: country = 'foo' $.ajax({ url: '/some-endpoint', success: function(data) { country = data.country; } }); console.log(country) // outputs 'foo' – Mark Simpson Jan 12 '13 at 07:46
  • 45
    @MarkSimpson - the reason it doesn't work is because in your example, the `console.log` is run immediately, but the ajax success function only runs at some point later when the ajax call actually returns a response. This is a fundamental point about the asynchronous nature of ajax: code in closure functions does not run in sequence with the code around it. This is an important to grasp when learning about event-driven code. – Spudley Jan 12 '13 at 12:10
  • The way to get the console.log to be more accurate in this case would be to put it inside the ajax success function. – DWils Jan 09 '14 at 17:13
  • 1
    Another of my brilliant insights: double check the spelling and case of the variable name. It is very easy to miss something as simple as sessionId vs sessionID. – whitebeard Jul 21 '16 at 10:04
  • I've the same problem on these. But finally understood, thanks @Spudley ! – Yudhistira Bayu Jan 14 '19 at 21:12
  • Anyone know why global variables become undefined in image.onload function? – Paul McCarthy Apr 28 '19 at 00:18
92
var a = 10;

myFunction();

function myFunction(){
   a = 20;
}

alert("Value of 'a' outside the function " + a); //outputs 20
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
Chris
  • 4,255
  • 7
  • 42
  • 83
  • 1
    thanks for this awesome simple example. The logic of this was doing my head in. Just got to get used to 4d thinking. – Mikey3Strings Jul 09 '16 at 17:56
  • 1
    @NullPoiиteя, but why adding this: var global = "Global Variable"; function click(){ global = "Hello World!"; }; console.log(global); return (
    ); } in react js, the global is not changed to Hello World ?
    – Asking Jan 05 '22 at 07:54
  • 1
    When you add `var` before `a` inside the function - `var a=20` -, the global value of a will not change. – Timo Aug 06 '22 at 07:59
  • also, if `a` is a function's parameter, it won't change the global variable – moser Aug 04 '23 at 22:05
38

Just use the name of that variable.

In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitely by typing the var keyword before the name of the variable.

If the name of the local value has the same name as the global value, use the window object

See this jsfiddle

x = 1;
y = 2;
z = 3;

function a(y) {
  // y is local to the function, because it is a function parameter
  console.log('local y: should be 10:', y); // local y through function parameter
  y = 3; // will only overwrite local y, not 'global' y
  console.log('local y: should be 3:', y); // local y
  // global value could be accessed by referencing through window object
  console.log('global y: should be 2:', window.y) // global y, different from local y ()

  var x; // makes x a local variable
  x = 4; // only overwrites local x
  console.log('local x: should be 4:', x); // local x
  
  z = 5; // overwrites global z, because there is no local z
  console.log('local z: should be 5:', z); // local z, same as global
  console.log('global z: should be 5:', window.z) // global z, same as z, because z is not local
}
console.log('global x: should be 1:', x); // global x
console.log('global y: should be 2:', y); // global y
console.log('global z: should be 3:', z); // global z
a(10)
console.log('global x: should be 1:', x); // global x, unaltered
console.log('global y: should be 2:', y); // global y, unaltered
console.log('global z: should be 5:', z); // global z, overwritten in function a

Edit

With ES2015 there came two more keywords const and let, which also affect the scope of a variable (Language Specification)

yunzen
  • 32,854
  • 11
  • 73
  • 106
  • 2
    +1 for describing the name collision between the global and the locally declared variable and how to access it. – gdbj Nov 27 '16 at 02:33
  • @yunzen, but why adding this: var global = "Global Variable"; function click(){ global = "Hello World!"; }; console.log(global); return (
    ); } in react js, the `global` is not changed to Hello World ?
    – Asking Jan 05 '22 at 07:53
  • Would anyone mind adding how to do this with _dictionaries_? Declaring `global.value=1` outside then doing `global.value++` inside any function will not increment it. Doing `global['value']+=1` does not help either. – scavenger Nov 27 '22 at 17:49
  • @scavenger I suppose you should start a new question with an code example of what you want to achieve – yunzen Nov 28 '22 at 07:43
11
var a = 10;

myFunction(a);

function myFunction(a){
   window['a'] = 20; // or window.a
}

alert("Value of 'a' outside the function " + a); //outputs 20

With window['variableName'] or window.variableName you can modify the value of a global variable inside a function.

Sterling Diaz
  • 3,789
  • 2
  • 31
  • 35
7
<script>
var x = 2; //X is global and value is 2.

function myFunction()
{
 x = 7; //x is local variable and value is 7.

}

myFunction();

alert(x); //x is gobal variable and the value is 7
</script>
Iman Sedighi
  • 7,624
  • 4
  • 48
  • 55
  • Just don't use the `var` keyword inside of the function, then you don't have to deal with `document.getElementById("outside").value = x;` – Ben Aubin Apr 26 '15 at 14:30
0

A simple way is to use var

var apple = null;
const some_func =()=>{
      apple = 25
}
some_func()
console.log(apple)
MD SHAYON
  • 7,001
  • 45
  • 38