'Scope assumption for a loop's variable [duplicate]

// i declared in (), not in {}
for(let i = 0; i < 5; i++){
  console.log("for:" + i);
}

console.log(i); // error

Why did it assume that variable i belongs to loop scope if it was declared outside the loop's body brackets?

I found this:

"Variables declared with let are local to the statement"

Source

Ok, but why is it so?



Solution 1:[1]

The main issue here is the type of variable you're saving the index value for. We have two solutions to solve this problem. First:

let i = 0; /* using let out of for loop */
for(;i < 5; i++){
  console.log("for:" + i);
}

console.log(i); // no error

Second:


for(var i = 0; i < 5; i++){ /* Using var */
  console.log("for:" + i);
}

console.log(i); // no error

Solution 2:[2]

One of the main difference between let and var is that let allows you to declare variables that are limited to the scope of a block statement:

{
  let a = 10;
}

console.log(a); // ReferenceError: a is not defined

at the same time var would work fine with that scenario.

Getting back to your example, the same is happening with for loop. So one of the solution, if you want to have an access to counter - is to create external variable and use it in your loop. You can also achieve the same result with while:

let counter = 0;

while(counter < 5) {
  // do stuff
  counter++;
} 

console.log(counter); // 5

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wraithdev3
Solution 2 Sergey Lk