简体   繁体   中英

variable created with “let” in global scope vs variable created with “var” inside a loop

I am trying to get some experience with the variable declarations in JavaScript. in the following code, whenever I try to define the variable inside the loop with var keyword it throws me an error:

"Uncaught SyntaxError: Identifier 'i' has already been declared".

whereas if I use "let" keyword (or no keyword at all) there is no problem. I know that in the case that I don't use any keyword, JavaScript uses the same variable in the global scope and overwrites it. I also know that variables created with "let" keyword are considered block scope and variables created with "var" keyword outside a function are considered global. but I don't understand this behavior! I would be grateful if anybody could shed illumination on this matter.

this code:

let i = 78;
console.log(i);
for (var i = 0; i < 4; i++) {
    console.log(i);
    var insideloop = 100;
}

console.log(i); gives this error: Uncaught SyntaxError: Identifier 'i' has already been declared

but this one has no problem an gives the following output:

let i = 78;
console.log(i);
for (let i = 0; i < 4; i++) {
    console.log(i);
    var insideloop = 100;
}
console.log(i);

Results: 78 0 1 2 3 78

The variables declared with var inside any block in the global scope are not local to that block(in your case its block of for loop) but they are inside global scope.

So in your first example you are trying to re declare the variable i which is already declared before in global scope with let .

 for(var i =0;i<5;i++){} console.log(i); //i is in global scope 

Where as let if declared in any block in your case its limited to the block of for loop. Its not present outside.

 for(let i =0;i<5;i++){} console.log(i); //i is in global scope 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM