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;
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"> </script>
Fiddle
PSL
source share