Search code examples
javascriptvariablesecmascript-6for-in-loop

Why JavaScript const works well with for in loop


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
}

Solution

  • 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.