why var declaration fast than let

前端 未结 1 2009
臣服心动
臣服心动 2021-01-21 02:21



        
相关标签:
1条回答
  • 2021-01-21 02:58

    It might be worth mentioning that in es6 the let keyword in a for-loop has been designed to solve the notorious closure in a loop problem in JavaScript:

    var log = msg => div.innerHTML += msg + "<br>";
    
    for (var i=0; i < 3; i++) {
      Promise.resolve().then(() => log(i)); // 3, 3, 3
    }
    for (let i=0; i < 3; i++) {
      Promise.resolve().then(() => log(i)); // 0, 1, 2
    }
    <div id="div"></div>

    As @loganfsmyth mentions in comments, it does this by effectively creating a new closure for each iteration of the loop.

    This, and the fact that the feature is new, might account for some of the performance difference seen in Chrome. That said, there seems to be no difference in Firefox for your particular example, so it seems possible for browsers to optimize this.

    0 讨论(0)
提交回复
热议问题