Why doesn't the for loop counter break after exiting the loop in javascript?

for(var i=0;i<5;i++){} alert(i); 

in javascript this will bring us 5 other languages ​​such as C ++, java, C # .... will just give an error that the variable I am not defined in context.

So why is the for loop counter not destroyed after exiting the loop in javascript?

+7
javascript
source share
3 answers

This is due to the fact that the JavaScript engine will move ("raise") the decoding of variables to the top of the function, regardless of where it is declared inside function 1 . JavaScript does not have a block scope.

 { //Some code for(var i=0;i<5;i++){} alert(i); //Some code } 

It is equivalent to:

 { var i; //.. some code for(i=0;i<5;i++){} alert(i); } 

1 If this exception does not fall into the catch clause; this variable is limited to a catch .

Update

To define variables for the scope region of a specification block, ecmascript 6 (javascript 1.7) introduces let . Currently, this will only work in the latest version of the FireFox browser and is under negotiation.

 <script type="application/javascript;version=1.7"> //Some code for (let i = 0; i < 10; i++) { alert(i); // 1, 2, 3, 4 ... 9 } alert(i); // Here you will get an error here saying ReferenceError: i is not defined. } </script> 

Fiddle

+11
source share

Javascript only creates areas for functions, with and catch blocks (with functions creating a scope for the var statement), which is equivalent to Java ( and does not work ):

 (function(){ for(var i=0;i<5;i++){} })(); alert(i); 
+3
source share

Variables in Javascript are var hoisting , where the variable becomes declared over the block by the javascript engine.

See Mozilla's Javascript Docs in var for an example of how this will work.

0
source share

All Articles