spirytus
spirytus

Reputation: 10946

Confused with hoisting in Javascript

Can anyone explain to me why if statement inside of bar has foo us undefined?

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

Upvotes: 1

Views: 38

Answers (2)

TGH
TGH

Reputation: 39258

The given code will be parsed like this:

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

The local foo is hoisted to the top of the function since JS only has function scope and no block scope. The "hoisted" variable will take precedence over the foo defined outside the function, which is why the variable is undefined in your if statement.

Upvotes: 2

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

// This foo is at the global level.
var foo = 1;
function bar() {
  // the compiler puts in this line:
    var foo;
    if (!foo) {
        // and the var here doesn't matter.
        foo = 10;
    }
    alert(foo);
}
bar();

Upvotes: 2

Related Questions