How do I change the value of a global variable inside of a function

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.


var a = 10;

myFunction();

function myFunction(){
   a = 20;
}

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

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.


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 5:', window.z, z) // global z, same as z, because z is not local
}
a(10);
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 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)

Tags:

Javascript