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?