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
6
  • 1
    possible duplicate of What is the scope of variables in JavaScript? Commented Feb 9, 2015 at 18:08
  • A Really good slideshow on Scope and this... you are not using this but still goes over scope well davidql.github.io/scope_talk/# Commented Feb 9, 2015 at 18:10
  • @Someone You're suggesting that this won't answer their question? Seriously? Commented Feb 9, 2015 at 18:10
  • 1
    Why do you expect it not to change? You don't have a local variable. Commented Feb 9, 2015 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. Commented Feb 9, 2015 at 18:11

4 Answers 4

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);
})();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. While I was reading your reply, it immediately made sense to me what I misunderstood.
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.

Comments

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);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.