3

I'm fairly well-versed on the differences between es6 let and const in general. What I'm not so sure about, is within the definition of a for..of loop.

I know that an "old-school" for loop signature will not accept const ie

for (let i = 0; i < 100; i++) ... // works in chrome

for (const i = 0; i < 100; i++) ... // does not work in chrome (reassignment error)

However, with a for..of loop, it does not seem to make a difference

const someArray = ['hello', 'hey'];

for (let elem of someArray) ... // works
for (const elem of someArray) ... // also works?

So what's going on here?

Why is const allowed in for..of but not an old-school for loop?

What is the ultimate result difference within the loop? (other than possibly reassigning elem within the loop which I wouldn't expect many people to be doing regardless)

D G
  • 371
  • 4
  • 12
  • 1
    _You can use const instead of let too, if you don't reassign the variable inside the block._ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of – Kevin Boucher May 21 '18 at 17:17
  • `const` is *allowed* in old-school loops as well (not a syntax error). You just cannot increment it. – Bergi May 21 '18 at 18:15
  • @Bergi yep i realized that while doing further research after asking this Q. Might as well drop this Q since it's a dupe anyway. My searches didn't find those :) – D G May 21 '18 at 18:17

1 Answers1

5

Only one variable is reassigned hence the error

for (const i = 0; i < 100; i++)

There is a separate variable created for each loop, hence, works fine

for (const elem of someArray)
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59