0

for(let i =0; i<10;i++){
    const a = i;               
    console.log(a);
}

const b = 5;
const b = 10;   

for(const i =0; i<10;i++){
    const a = i;                
    console.log(a);
} 

enter code here

In above code b is declared twice so system is giving an error. Uncaught SyntaxError: Identifier 'b' has already been declared

In the for loop, the constant variable will be declared as many time as the loop runs. Why its not an error?

In the second loop why the const i throwing an error? Is const i in the for loop initialisation have a different scope?

nt314
  • 29
  • 2
  • Because in the loop the variable is not created twice in the same scope, `const` can be declared in a block scope, and each round of the `for` loop creates its own scope. – Teemu Jan 22 '22 at 14:41
  • Each loop *iteration* has its own scope. (And `for` plays a bit of a clever game copying the `i` from the previous scope to the `i` for the new one just before doing the update expression.) – T.J. Crowder Jan 22 '22 at 14:45
  • @T.J.Crowder If that's the case then why this throws an error? -----> for(const i =0; i<10;i++){ } – nt314 Jan 22 '22 at 15:23

0 Answers0