What's the action scope of for-loop in ES6?

后端 未结 3 1702
庸人自扰
庸人自扰 2021-01-04 12:11

What\'s exactly the action scope of let in a for-loop in JavaScript?

3条回答
  •  既然无缘
    2021-01-04 13:10

    ECMAScript 2015 has a particular clause1 to cover what a for loop does when it has a variable defined with let in the control structure.

    My reading of it is that it is specifically designed to provide a separate environment record for the variable within the loop body so that its value in a loop iteration will be seen by nested functions used as call backs - and in the process obviating the need to capture the value of a loop variable in a closure.

    Essentially

    for( let i=0; condition; ++i) {
        ...
    }
    
    • creates an environment record for the loop body with a binding for i set to zero;
    • executes the loop body
    • creates a new environment record for the next iteration, increments i and stores the result in the new environment record for the next loop iteration (if it executes).

    Comparing the behavior with block scoping of variables within curly braces is misleading - the lexical scoping of the variable to the for loop body does not require block braces to be used:

    for( let i = 0;  i < 2; ++i) continue;
    console.log( i);

    So the body scoping of the let variable is a language design "special".

    1Refer to CertainPerformance's answer for technical details of the specification.

提交回复
热议问题