2

Trying to understand fundamentals of javascript I ran into a following code and expected value of variable named "foo" would be 7 and 5 however it came out as 7 and 7. Not sure why....

var foo = 5;
(function Test() {
    foo = 7;
    console.log("foo=" + foo);
})();
console.log("foo=" + foo);

foo=7
foo=7
DaeYoung
  • 1,161
  • 6
  • 27
  • 59
  • 1
    possible duplicate of [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – ncksllvn Feb 09 '15 at 18:08
  • A Really good slideshow on Scope and this... you are not using this but still goes over scope well http://davidql.github.io/scope_talk/#/ – w3bMak3r Feb 09 '15 at 18:10
  • @Someone You're suggesting that [this](http://stackoverflow.com/a/500459/1854575) won't answer their question? Seriously? – ncksllvn Feb 09 '15 at 18:10
  • 1
    Why do you expect it not to change? You don't have a local variable. – SLaks Feb 09 '15 at 18:11
  • 1
    It is because he is declaring foo before he calls the function so it is modifying the same variable. Foo is not local scope to just that anonymous function. – w3bMak3r Feb 09 '15 at 18:11
  • if the inner variable was declared as a local variable with the var keyword it would print 7..5 – Franz Sittampalam Feb 09 '15 at 18:14

4 Answers4

3

Because when you do foo = 7; it makes a global variable and sets it to 7, even after the function is done it's still 7. You probably want it to be a local variable:

(function Test() {
    var foo = 7;
    console.log("foo=" + foo);
})();
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
2

To get 7 and 5, you need to put "var" before "foo = 7;" in your function in order to keep it from overwriting the the global foo you declared outside the function.

That is, you need to use var when declaring variables within functions to make them locally scoped to the function.

0

You are declaring a global variable and then referencing it inside your function. if you want a local variable, declare it inside your function using the var keyword.

//foo variable definition here
var foo = 5;

(function Test() {
    //Referencing the already globally defined var.
    //Use var foo = 7 in order to define a new local var.
    foo = 7;
    console.log("foo=" + foo);
})();
console.log("foo=" + foo);
Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54
0

Referencing a global variable inside an immediately called anonymous method doesn't mean it overrides the variable in the global scope!

Something like foo=7 will create a new variable only if there is no other foo that is accessible from the current scope. Which in this case exists!

Immediately called Anonymous function is not a completely isolated scope. As a function, it has a local scope, which is not available outside the block. But it still have access to the global scope.

Amanuel Nega
  • 1,899
  • 1
  • 24
  • 42