183

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?

0

6 Answers 6

193

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.

6
  • 3
    This doesn't work for me: country = 'foo' $.ajax({ url: '/some-endpoint', success: function(data) { country = data.country; } }); console.log(country) // outputs 'foo' Commented Jan 12, 2013 at 7:46
  • 46
    @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
    Commented Jan 12, 2013 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
    Commented Jan 9, 2014 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
    Commented Jul 21, 2016 at 10:04
  • I've the same problem on these. But finally understood, thanks @Spudley ! Commented Jan 14, 2019 at 21:12
99
var a = 10;

myFunction();

function myFunction(){
   a = 20;
}

alert("Value of 'a' outside the function " + a); //outputs 20
4
  • 1
    thanks for this awesome simple example. The logic of this was doing my head in. Just got to get used to 4d thinking. Commented Jul 9, 2016 at 17:56
  • 1
    @NullPoiиteя, but why adding this: var global = "Global Variable"; function click(){ global = "Hello World!"; }; console.log(global); return ( <div className="App"> <button onClick={click}>click</button> </div> ); } in react js, the global is not changed to Hello World ?
    – Asking
    Commented Jan 5, 2022 at 7:54
  • 1
    When you add var before a inside the function - var a=20 -, the global value of a will not change.
    – Timo
    Commented Aug 6, 2022 at 7:59
  • also, if a is a function's parameter, it won't change the global variable
    – moser
    Commented Aug 4, 2023 at 22:05
39

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)

4
  • 2
    +1 for describing the name collision between the global and the locally declared variable and how to access it.
    – gdbj
    Commented Nov 27, 2016 at 2:33
  • @yunzen, but why adding this: var global = "Global Variable"; function click(){ global = "Hello World!"; }; console.log(global); return ( <div className="App"> <button onClick={click}>click</button> </div> ); } in react js, the global is not changed to Hello World ?
    – Asking
    Commented Jan 5, 2022 at 7: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
    Commented Nov 27, 2022 at 17:49
  • @scavenger I suppose you should start a new question with an code example of what you want to achieve
    – yunzen
    Commented Nov 28, 2022 at 7:43
12
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.

1
  • This is the only way I could change the global variable value in angular component !!! Commented Feb 14, 2020 at 2:01
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>
1
  • 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
    Commented Apr 26, 2015 at 14:30
0

A simple way is to use var

var apple = null;
const some_func =()=>{
      apple = 25
}
some_func()
console.log(apple)
1
  • 4
    Does not work when use async function and await for set value.
    – e-info128
    Commented Aug 29, 2021 at 6:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.