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