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

前端 未结 4 966
日久生厌
日久生厌 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:08

    Yes. This is indeed expected behavior.

    const defines a variable which, as the name suggested, stays constant. That means the value of a const cannot change.

    Now what you do in your for loop is incrementing "i", which was defined as a constant.

    for (const i = 0; i < 3; i++ /* <- this doesn't work */ ) {
        console.log(i);
    }
    

    with for .. in or for .. of however, you just bind the variable.

    In other words: With for .. in/off, the variable gets assigned once before execution of the loop and not on every iteration. Therefore const can indeed be used.

    As for the reference:

    ForDeclaration : LetOrConst ForBinding

    http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-in-and-for-of-statements-static-semantics-boundnames

提交回复
热议问题