0

Working with a vanilla Javascript project, I stumbled upon a piece of code that declared multiple const inside a for...of loop. Trying to understand how it worked, I replicated it using an MDN example on the for...of docs:

const iterable = 'abc';

for (const value of iterable) {
  const iterableAgain = value + " Again!";
  console.log(iterableAgain);
  console.log(value);
}

...the code below will show:

a Again!
a
b Again!
b
c Again!
c

This means that const is being re-declared each loop. How is this possible? I thought const and let couldn't be redeclared without throwing TypeError, besides some circumstances. Is this a case of variable shadowing? If so, does that mean that every iteration in a for...of consist of a different variable block?

Note: Stack Overflow threw me similar questions that have been asked, but to clarify, none have been made related plain Javascript, all of those have been asked related to Typescript.

  • 1
    "*This means that const is being re-declared each loop*" it's not **re-**declared. It's just a different const binding each loop. – VLAZ Jan 07 '21 at 08:00
  • 2
    That's how block scope works, the variable is unique for every round, i.e. it's re-created, not re-assigned. – Teemu Jan 07 '21 at 08:00
  • That's the part I don't get: Why is it able to use the exact same name on each loop? If it was outside a loop, it woud throw an "error: unknown: Identifier 'iterableAgain' has already been declared". Edit for Teemu's comment: Does that mean that each "for...of" iteration is its own scope? – LihuelWorks Jan 07 '21 at 08:02
  • Because Javascript specifically allows for this as sort of a special case, since it makes a lot of sense and solves a number of common problems. – deceze Jan 07 '21 at 08:04
  • Every round of the loop is executed in its own scope, that's what we call "block scope", and that's why you can use `const` to declare the variable. – Teemu Jan 07 '21 at 08:04
  • This will help you a lot to understand whats going on: https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript – Kai Lehmann Jan 07 '21 at 08:08
  • @KaiLehmann I don't think the article addresses the scenario shown here. – VLAZ Jan 07 '21 at 08:12

0 Answers0