I was studying the concept of variable scope in JS, found this example on it:
(function() {
var foo = 1;
function bar() {
var foo = 2;
}
bar();
console.log(foo) //outputs 1
if(true) {
var foo = 3;
}
console.log(foo) //outputs 3
})();
output of this function is
1
3
Now I am confused how come foo
gets gets value 3 in second log. even when foo
is declared by using var
in if
statement. shouldn't the foo
declared in if
will have a new instance as it gets in bar()
??