2

I know global variables are created when they are declared outside a function (says W3Schools).

If I create a global variable and edit it in a function, does it become local? Does the new value given by the function become the global value?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
apparatix
  • 1,492
  • 7
  • 22
  • 37

4 Answers4

8

In general, no, editing a global does not make it local:

var myglob = 5;
function incGlob() {
    myglob = myglob + 1;
}

incGlob();
console.log(myglob); // is 6 now

However, if you pass the global variable as an argument, the argument is a local copy:

var myglob = 5;
function incArg(myloc) {
    myloc = myloc + 1;
}

incArg(myglob);
console.log(myglob); // is still 5

Note that objects are passed by reference, so editing the member variables of an argument variable changes the member variables of the original object passed in:

var myglob = { foo:5 };
function editLoc(myloc) {
    myloc.foo = 6;
}

editLoc(myglob);
console.log(myglob.foo); // foo is 6 now

Finally, note that the local variable in editLoc, above, is just a reference. If we try to overwrite the entire object (instead of a member variable), the function simply loses the reference to the original object:

var myglob = { foo:5 };
function clobberLoc(myloc) {
    myloc = { bar:7 };
}

clobberLoc(myglob);
console.log(myglob.foo); // myglob is unchanged...
// ...because clobberLoc didn't alter the object,
// it just overwrote its reference to the object stored in myglob 
apsillers
  • 112,806
  • 17
  • 235
  • 239
5

No, editing the global variable will not change the variable's scope. The new value assigned becomes the global value.

http://jsfiddle.net/RtnaB/

myGlobal = 'foo'; // notice no 'var' keyword, implicitly global (DON'T DO THIS)

console.log(myGlobal); // logs 'foo'

var myFunc = function () {
    myGlobal = 'bar';
};

myFunc();

console.log(myGlobal); // logs 'bar'
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • 1
    I prefer `window.myGlobal = 'foo'` instead of `var myGlobal` because the use of `var` is misleading outside of a function... (it is *not* a lexical variable, but a property and does not work with the same closure rules) –  Jun 04 '12 at 19:48
3

Yes.

You will only create a local variable if you use the var keyword to declare it inside a function.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Nope. I just did it. `var` does nothing. The declared variable inside the function, will still point to the global variable. –  Oct 03 '16 at 12:55
  • @Bear: No; `var` does create a local scope. Show me a demo. – SLaks Oct 05 '16 at 14:28
2

The new value becomes the global value.

Josh Mein
  • 28,107
  • 15
  • 76
  • 87