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

前端 未结 3 529
北恋
北恋 2020-12-20 17:13
for(var i=0;i<5;i++){}
alert(i);

in javascript this will get us 5 other languages like C++, java, c# .... will simply give an error that the i v

3条回答
  •  温柔的废话
    2020-12-20 17:59

    This is because the JavaScript engine will move ("hoist") the variable decalaration to the top of the function no matter where it is declared inside the function1. JavaScript does not have block scope.

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

    Is equivalent to:

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

    1 Unless it's the exception being caught with a catch clause; that variable is scoped to catch block.

    Update

    For defining block scope variables ecmascript 6 specs (javascript 1.7) introduces let. Currently this will work only in latest version of FireFox browser and in consensus stage.

    
    

    Fiddle

提交回复
热议问题