Inconsistent scope rules of variables in for, for-in and for-of loops

前端 未结 4 975
日久生厌
日久生厌 2020-12-07 03:25

So I noticed that I have to use let inside a for loop, and cannot use const. However, I found that I can use const inside

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 04:18

    Your first question has been answered by @NullDev, so I'm going to the second:

    This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded.

    "These variables are not local to the loop" means the counter created by var keyword. If you use let then the scope of the counter is only in that for loop. This is another expected behavior since var has the wideless scope. And yes, the documentation is a little bit ambiguous.

提交回复
热议问题