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

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

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

3条回答
  •  醉梦人生
    2021-01-04 13:13

    Variables declared with let are not visible (accessible) outside their scope, which explains the error raised by the console.log that is outside the for loop).

    It also explains why the loop runs three times and prints 4, the explanation is that the i inside the for loop block (the one declared as let i = 4;) is different than the i in the loop header due to the invisibility that comes with the let keyword, i.e., the i in let i = 4; which is inside the for loop block is not visible in the for (let i = 0; ...), they're different, and so the one inside the block is not affecting the one outside (in the header).

提交回复
热议问题