Why JavaScript const works well with for in loop [

2019-08-10 07:12发布

This question already has an answer here:

Why JavaScript const works same as let in for in loop? const is using to declare constants in EC6. Then why the const num value getting updated in each iteration of the for in?

For in with let

for (let num in nums) {
    console.log(num); // works well, as usual
}

For in with const

for (const num in nums) {
    console.log(num); // why const value getting replaced
}

3条回答
小情绪 Triste *
2楼-- · 2019-08-10 07:51

Why JavaScript const works same as let in for in loop?

By definition, const is block scoped like let.

Then why the const num value getting updated in each iteration of the for in?

It isn't. Since it is block scoped, each time you go around the loop the old constant drops out of scope and you create a new one.

查看更多
倾城 Initia
3楼-- · 2019-08-10 07:51

Why the const num value getting updated in each iteration of the for in?

It isn't getting updated. Similar to let, it is scoped to the loop block and creates a new const variable on every iteration, initialised with the respective property key.

查看更多
虎瘦雄心在
4楼-- · 2019-08-10 07:53

Maybe (not sure) is for the scope in which it's declared. It seems you are declaring the constant in the scope of the for statement, so it gets removed and redeclared every new iteration. So each time it has a different value.

It's a guess, not sure...

查看更多
登录 后发表回答