0

When I declare a variable by let keyword more than one time with the same variable name, I know it is showing an error Uncaught SyntaxError: Identifier 'variable name' has already been declared.

For example (1)*:

let v = "1";

let v = "1";

But when I declare many variables with the same name in a loop, I do not know why it is not showing the same error.

For example (2)*:

for(let i = 0; i<=2; i++){

    let v = "1"

}

Already I know there is a logical explanation for it but I do not know what

Note: Assume that Declaring the first two variables in example(1) in JS file, and creating the loop in example(2) in another JS file

This question has been answered before but it was deleted by mistake so I repost it with the answer.

Ali Hsaino
  • 131
  • 9

1 Answers1

1

Each iteration of the loop is a new scope.

Like when you declared variable with v name regardless of it is value in global scope and declare a variable with v name in if statement scope, The program will not show any errors because two variables are not in the same scope

for example :

//glopal scope
let v = "1"
console.log(v) // output : 1

//if statement scope
if(true === true){
 let v= "2"
 console.log(v) // output : 2
}

//also in global scope after if statement scope 
console.log(v) // output : 1

So the same situation is happen with the loop because Each iteration of the loop is a new scope.

Ali Hsaino
  • 131
  • 9