2

We know that let and const are not hoisted.

So code like this throws an error

let x = 33;
let x = 99;

SyntaxError: Identifier 'x' has already been declared

Now since let variables are limited to the scope of a block statement, something like the following is assumed to generate the same error as the code above!

for (let i = 0; i < 10;) { // i here declared in this for loop block
    let i = 11; // i here is in the same for loop block
    console.log(i);
    break;
}

But surprisingly does not!

output

11

Why let i here is treated like it's declared in a different block? or it's like a totally different variable?

Community
  • 1
  • 1
Rain
  • 3,416
  • 3
  • 24
  • 40
  • 1
    The `for (let i` in fact declares it outside of the block - though in a per-iteration scope. The `{ … }` body of the loop is a new block with its own scope. – Bergi May 12 '20 at 11:14
  • 1
    So basically you'd need to write `for (let i=0; i<5; i++) let i;` to get the collision, but that's a syntax error for a different reason already. – Bergi May 12 '20 at 11:20

0 Answers0