DaeYoung
DaeYoung

Reputation: 1229

global and local variable execution context in javascript

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

Upvotes: 2

Views: 398

Answers (4)

Amanuel Nega
Amanuel Nega

Reputation: 1977

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.

Upvotes: 0

Nick Louloudakis
Nick Louloudakis

Reputation: 6005

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

Upvotes: 0

Michael Dziedzic
Michael Dziedzic

Reputation: 543

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.

Upvotes: 2

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

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

Upvotes: 3

Related Questions