3
for(let i = 0; i < 5; i++) {
    console.log(i); //outputs 0, 1, 2, 3, 4
}

HERE ↓ IS THE DOUBT

for(let i = 0; i < 5; i++) {
    let i = 2;
    console.log(i); //output 2 five times
}

Why am I able to initialize and assign the i variable twice, as I know we can only initialize and assign the variable declared with let once and later can reassign it another value. For example:

let j = 5;
let j = 6;
console.log(j); //error > Identifier 'i' has already been declared

let k = 5;
k = 6;
console.log(k); // output 6
Boann
  • 48,794
  • 16
  • 117
  • 146
  • inside the for loop, the let created scope only for one time, and update the value. it doesnt create let variable again and again. So assiging to same mutable var is ok. However, the second case is not true. – xdeepakv Nov 09 '19 at 19:14
  • 2
    This is an interesting question because the `let i` from the `for` loop declaration is kept separate for each invocation of the loop, but is apparently not a full-fledged `let i` inside the `for` loop, otherwise it would conflict with the redefinition and be an error. It must have to do with the "special" treatment that the `for` loop variable gets. It would be interesting to see the actual ECMAScript reference that explains how the `for` loop `let i` works. – jfriend00 Nov 09 '19 at 19:19

3 Answers3

2

It's like the form of:

let j = 5;
{
  let j = 6;
  console.log(j); //6
}
console.log(j); //5
Addis
  • 2,480
  • 2
  • 13
  • 21
1
for(let i = 0; i < 5; i++) {
    let i = 2;
    console.log(i); //output 2 five times
}

In second line, just because {} brackets. You are crating a new scope. For more please go through link

let j = 5;
let j = 6;
console.log(j);

Here no scope diffrence, so error.

let k = 5;
k = 6;
console.log(k);

Here both k are in same scope. and you are re-assigning value.

mukund patel
  • 1,039
  • 10
  • 31
1

The letdeclaration keeps the variable only within the scope. How Javascript handles scope for for iterative loop is that a new scope is started every iteration. The var keyword will leak the variable into the global scope and maintained every iteration, whereas the let will allow a new i to be declared. For more details, here's a Babel compiled javascript which we can see the actual variables being used and understand this scoping anomaly better! https://stackoverflow.com/a/44367144/8181001

peekolo
  • 342
  • 3
  • 8