Can anyone explain me that why dosent this code show error when we have redeclared let x=5 in this code? It should show error due to lexical scoping .
function demoFunction() {
let x = 10;
function demo() {
let y = 20;
let x=5;
console.log(x);
console.log(y);
}
console.log(x);
demo();
}
demoFunction();
Can anyone explain me that why dosent this code show error when we have redeclared let x=5 in this code? It should show error due to lexical scoping .
2
Answers
You can see this is acceptable from the first example in MDN’s documentation for let. Further down you can see this quote:
The key being "same scope".
From MDN’s definition of scope:
Both declarations of
x
in your example are in two different function scopes, so this is acceptable. Note that unlikevar
,let
will create an entirely new variable. Note that you can also reference variables that are not in the same scope, but are in an enclosing scope. The chain of enclosing scopes is referred to as a scope chain. When referencingx
, the interpreter will take the firstx
it finds in the scope chain.In that snippet, there are 6 distinct variables (one
x
, twoy
s and threez
s). Which variable gets referenced depends on which scope I am doing the referencing. The interpreter will take the closest one in the scope chain.You’re not getting any sort of lexical scoping error because variables declared with let and const keywords are block-scoped (In strict mode). Since functions are also block-scoped, variables declared within certain block are accessible within that function. But, every function has its own separate execution context which gets called in a call stack internally one by one.
These two variables have two different scope and two different execution contexts, that’s why it’s not showing any sort of error.