Search code examples
javascripthoisting

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

Solution

  • // 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();