weiheli
weiheli

Reputation: 97

why can "for in" use const in JS?

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

Answers (4)

spender
spender

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

AtaiLo
AtaiLo

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? example for in

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

Tadeo Hepperle
Tadeo Hepperle

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

sjahan
sjahan

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

Related Questions