answer99
answer99

Reputation: 251

JavaScript scopes on local and global variable

Here is the Code:

var foo = 1;
function bar() {
    alert(foo)
    if (!foo) {
        var foo = 10;
    }
    alert(foo);
}
bar();

While foo is the Global variable. After calling the b() function, foo is alerting as the undefined. As it is global variable it should alert as 1 Right? If i am wrong please correct me.

JSfiddle

Upvotes: 0

Views: 30

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

No... since you are declaring foo inside the bar function as a local variable the global instance will not be accessed while using foo inside the function.

You are getting undefined because of variable hoisting, where all variable declaration will be moved to the top of the function so at execution your function will look like

var foo = 1;
function bar() {
    var foo;
    alert(foo)
    if (!foo) {
        foo = 10;
    }
    alert(foo);
}
bar();

Upvotes: 1

Quentin
Quentin

Reputation: 943152

You have two variables called foo.

One declared on line 1, which is global and another declared on line 5, which is local to the bar function.

Remember that var statements are hoisted, so if you have a local variable for a function, it is local for all of the function.

When you alert the value for foo on lines 3 and 7, you are alerting the local foo.

Upvotes: 3

Related Questions