Reputation: 97
const arr = [1, 2, 3]
for (let i = 0; i < arr.length; i++) { // can't use const
console.log(i, arr[i]);
}
for (const i in arr) { // const is ok
console.log(i, arr[i]);
}
Why can "for in" use const but "for" can't?
Upvotes: 4
Views: 141
Reputation: 120450
As per my comment:
In the first case, the loop variable is mutated (i.e. it exists external to the scope of the loop body). In the second case, an entirely new
i
is supplied for each loop iteration, so no mutation is required.
However, the choice of block-scoped/function-scoped (let
/const
vs var
) declaration has an impact on the way that captured loop variables are treated. Run the code below and notice how using var
causes output that most users would not expect.
const captured = [];
for (var i = 0; i < 2; ++i) {
captured.push(() => console.log(i));
}
for (let i = 2; i < 4; ++i) {
captured.push(() => console.log(i));
}
for (const i of [4, 5]) {
captured.push(() => console.log(i));
}
for (var i of [6, 7]) {
captured.push(() => console.log(i));
}
for (let i of [8, 9]) {
captured.push(() => console.log(i));
}
captured.forEach(v => v());
Upvotes: 0
Reputation: 111
A quote from this article (https://medium.com/@mautayro/es6-variable-declaration-for-loops-why-const-works-in-a-for-in-loop-but-not-in-a-normal-a200cc5467c2) says:
"What about using const in a for…in or a for…of loop though?
Weird, it looks like this works!
Upon deeper inspection of these types of for loops, it seems that they create a new block scope with each iteration. That would mean that each new index is actually a new variable within a new scope & our constant is never reassigned."
This article describes it pretty good: https://medium.com/@mautayro/es6-variable-declaration-for-loops-why-const-works-in-a-for-in-loop-but-not-in-a-normal-a200cc5467c2
Upvotes: 0
Reputation: 682
in the const element in arr
the element is the same as element in the const element = arr[i]
in the classical forloop. It is a constant variable with local scope, so it is declared and destroyed in each iteration.
Upvotes: 1
Reputation: 5950
You can't use const
in the first loop because of i++
which will reassign the variable i
.
In the for in
loop, i
can be a const
because it is defined for each iteration.
Upvotes: 5