I am trying to understand how Javascript handles re-declaring of the let variable in the sub-block of the current scope.
Variables declared by
let
have their scope in the block for which they are defined, as well as in any contained sub-blocks.
If we try this, it works fine as expected:
function letTest() {
let x = 1;
for(var i = 0; i < 1; i++) {
console.log(x); // logs - 1
}
}
Another example. Now I use the for
sub-block to assign a new value to let
variable of 0
and go through the for
loop.
As well this works as expected.
function letTest() {
let x = 5;
console.log(x); // logs – 5
for( x = 0; x < 12; x++) {
console.log(x); // logs – 0, 1, 2, 3, 4, 5, 6, … 10, 11
}
console.log(x); // logs - 12
}
But what happens when we re-declare and assign new value to the same variable x
by using keyword let
inside of the for
sub-block :
function letTest() {
let x = 5;
console.log(x); // logs – 5
for( let x = 0; x < 12; x++) {
console.log(x); // logs – 1, 2, 3, 4, 5, 6, … 10, 11
}
console.log(x); // logs - 5
}
What mechanism is here at work and what exactly happened?
Why is the value of let x = 5
not changed, why is there now 2 let
variables with the same name?
I believe I found the answer here:
Demystifying JavaScript Variable Scope and Hoisting
In JavaScript, variables with the same name can be specified at multiple layers of nested scope. In such case local variables gain priority over global variables. If you declare a local variable and a global variable with the same name, the local variable will take precedence when you use it inside a function. This type of behavior is called shadowing. Simply put, the inner variable shadows the outer.
and here as well:
https://stackoverflow.com/a/11901489/6375464
In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed...