0

I found a little bit strange behavior in this code:

for (let i = 1; i < 2; i++) {
  let i = 10;
  console.log(i);
}

I expected it to throw Syntax Error, because of doubled declaration, but it works and prints 10. Maybe, somebody could explain? Why it is not the same environment and performs shadowing? Thanks

Ilya S.
  • 3
  • 1
  • 1
    You are able to re-assign and overwrite let variables within a function scope. It's when let variables are re-declared in global scope that you will encounter the error, telling you that *let i* has already been defined. This post: https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav covers it pretty well. – Martin Oct 03 '18 at 11:04
  • @Martin, I`ll check post, thanks! – Ilya S. Oct 03 '18 at 11:14

3 Answers3

2

You are able to re-assign and overwrite let variables within a function scope. It's when let variables are re-declared in the same scope that you will encounter the error, telling you that let i has already been defined. This post covers it pretty well.

One of the main reasons to use let variables is when you are working with constrained memory, since let variables are strict. You are however able to work with the variable inside a function scope, as the altering of the variable is within that scope only. The syntax error that you are referring to in your question only occurs when the variable is re-declared in the same scope.

Martin
  • 2,326
  • 1
  • 12
  • 22
0

You cannot re-declare the same variable within the same scope.

let scope = "declaration one";
let scope = "declaration two"; //error

However, each scope can have its own declaration of a variable and inner scopes can override parent scopes but only temporarily while the scope lasts.

let scope = "outer scope";

if (true) {
  let scope = "inside if scope";
  console.log(scope);
}

console.log(scope);

{
  let scope = "inside block scope";
  console.log(scope);
}

console.log(scope);

So, with the for loop, the initialisation phase is before the new scope introduced by the body, hence you can re-declare the variable inside.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
0

Within same scope, you are not allowed to re-declare some variable. Scope is defined by curly brace/{}. Within {} you can not re-declare some variable. Try this

for (let i = 1; i < 2; i++) {
    let i = 10;
    let i = 20;
    console.log(i);
}

This will throw an error. Because i is re-declared here. The confusion is about loop control variable i. Control variable has reference to the loop scope. Control variable i is not within the scope of declared i within {}. Thats why this is working.

Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21