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 -
foo
is printing undefined
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? foo
from var
to let
, the logger inside the function foo
prints name from global scope. How this is working?Yes this is because the variables declared with var
have function scope and they are hoisted to the top of the function
. It logs undefined
due to hoisting.
Variables declared with let
have block scope so until the if
block is not executed the variable name
is not declared.
Even if you change it with if(true)
it will not work because the variable will only be available inside the block. {}
not outside.
Here is the example how let
works.
if(true){
let x = 3
}
console.log(x);