This question already has an answer here:
- ECMAScript 2015: const in for loops 3 answers
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
}
By definition,
const
is block scoped likelet
.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.
It isn't getting updated. Similar to
let
, it is scoped to the loop block and creates a newconst
variable on every iteration, initialised with the respective property key.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...