Why can I access the variable i outside the loop in which it was used?
Example:
for (var i = 0; i <= 10; i++) { console.log(i); } console.log(i, ' :вне цикла'); Why can I access the variable i outside the loop in which it was used?
for (var i = 0; i <= 10; i++) { console.log(i); } console.log(i, ' :вне цикла'); You can access the variable i , because it is declared via var , and all variables declared in this way " float " to the beginning of the parent function even from a nested block.
var variable: function f() { if (true) { var variable = 10; } return variable; } console.log(f()); var variable in reality: function f() { //Начало функции var variable; if (true) { variable = 10; } return variable; } console.log(f()); If you want to limit the visibility of this variable inside a for loop, use let instead of var .
for (let i = 0; i <= 10; i++) { console.log(i); } console.log(i, ' :вне цикла'); The scope of a variable declared via let limited to the block in which it is declared.
Source: https://ru.stackoverflow.com/questions/896279/
All Articles
for(let i = 0; i <= 10; i++).... - Teapot