3

Check this fiddle or the below code and tell me why is the output of this script is 10

var foo = 1;
function bar() {
    if (!foo) {
        var foo = 10;
    }
    alert(foo);
}
bar();
SharpCoder
  • 18,279
  • 43
  • 153
  • 249

1 Answers1

5

Because the var in the function, hoists the variable up to the top. As if you declared it at the top of the function, and so foo is treated as a local variable in the current scope, the foo in the global scope is not affected. Your code is the same as this:

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

As you can see, foo is declared at the top of the function and is undefined, but importantly doesn't get a value until inside the if statement.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • Is there way to check how the code is actually interpreted? – SharpCoder Apr 27 '14 at 14:55
  • Can you please explain me what is going on here http://jsfiddle.net/4Wx8j/ as well. I know its something to do with hoisting but I dont really understand why – SharpCoder Apr 27 '14 at 14:57
  • You're correct, it's hoisting. Declaring a function like `function ()...` means it will be hoisted up to the top of its parent, just like the `var` in the answer. So the function is declared as `a`, which makes `a` a local, you then assign `1` to `a`, so it's no longer a function, but still treated like a local variable, so the global isn't affected. You can test this theory by changing the inner function to `c`, then you see that the global `a` is modified. I'm not aware of any tool that shows how it's interpretted, but once you understand what is hoisted and what isn't, it's easy to see. – MrCode Apr 27 '14 at 15:38
  • Thanks MrCode. I like your explanation and your name. MrCode is such a cool name :) – SharpCoder Apr 27 '14 at 16:00