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 should it not be used? - Grundy
  • 2
    Because the scope of the variable is limited to functions, not cycles. - Alexxosipov
  • Related question: Stackoverflow.com/q/693868/183458 - Regent
  • one
    because inside the loop, the variable must be declared via let (that is, for(let i = 0; i <= 10; i++) .... - Teapot

1 answer 1

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.

As you can see the var variable:

 function f() { if (true) { var variable = 10; } return variable; } console.log(f()); 

How the interpreter sees the 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 .


Living example:

 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.