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

3
  • This works because with each iteration you get a new variable, which is scoped only to that iteration. Commented Sep 2, 2021 at 3:06
  • Does this answer your question? Why does const work in some for-loops in JavaScript? Commented Sep 2, 2021 at 3: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 Commented Sep 2, 2021 at 3:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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); }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.