0

I am confused about how const is used in javascript.

for (let stat of allStats){
        const index = allStats.indexOf(stat);

        console.log(filenames[index], stat.isFile());
    }

For example in the above code, "const index" within the for loop is being assigned different values in each iteration. How is that possible. I mean once a value is assigned to a const variable, can it be changed?

What have I misunderstood here..?

theju112t
  • 37
  • 9
  • This works because with each iteration you get a new variable, which is scoped only to that iteration. – Bishan Sep 02 '21 at 03:06
  • Does this answer your question? [Why does const work in some for-loops in JavaScript?](https://stackoverflow.com/questions/41067790/why-does-const-work-in-some-for-loops-in-javascript) – Bishan Sep 02 '21 at 03:07
  • @Bishan this is a not a duplicate of that question. That question is referring to the use of `const` in the header of a for loop (traditional for loop, for-of loops, and for-in loops), while this question pertains to the body of the for loop, regardless of what type it is – Samathingamajig Sep 02 '21 at 03:20

2 Answers2

5

const only means that the identifier declared with const in the scope in which it's visible can't be reassigned.

Here, each iteration of the loop has a different binding for index - you have a separate index for every iteration, so no variable is being reassigned.

Another way of looking at it:

function parseStat(stat) {
    const index = allStats.indexOf(stat);
    console.log(filenames[index], stat.isFile());
}
for (let stat of allStats){
    parseStat(stat);
}

would be just fine too - the index identifier is local to the parseStat function, just like in your original code, the index identifier is local to each iteration of the loop.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I think I understand it now but the concept that each iteration of the loop has a different "scope" is a different idea than what I am used to. – theju112t Sep 02 '21 at 04:09
1

1) let and const are true block scope. they are only visible only within the block they are declared in.

const arr = [1, 2, 3, 4];
for (let val of arr) {
  const double = val * 2;
  console.log(double);
}

console.log(double); // ReferenceError: double is not defined

2) Each loop iteration gets its own block variables. It is similar like you get its own local variables each time you invoke a function.

const arr = [1, 2, 3, 4];
for (let val of arr) {
  const double = val * 2;
  console.log(double);
}
DecPK
  • 24,537
  • 6
  • 26
  • 42