What is the scope chain in following code snippet -
var name = 'John';
function foo() {
if (false) {
var name = 'James';
}
console.log(name);
}
foo();
I got couple of queries regarding this -
- Why the logger in function
foo
is printingundefined
even when the variable is available in global scope? Is it due to the fact that same variable is re-declared in conditional falsy block and so the global variable is getting removed from the scope? - Also if we replace the variable declaration under if statement inside function
foo
fromvar
tolet
, the logger inside the functionfoo
prints name from global scope. How this is working?