2

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

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
  • 1
    Possible duplicate of [What's the difference between using "let" and "var"?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var). it's because of the scope. – Madhawa Priyashantha May 11 '19 at 03:51

1 Answers1

0

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
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • Thank you for your reply... I understand what you say but, if I were to declare the external `i` with `var` and redeclare it inside the loop, JavaScript would not complain and reassign the same variable with the new value! I assume that `var` keyword cannot overwrite a variable which has been created by `let` keyword. am I correct? – daniel hamidi May 12 '19 at 05:22
  • `var i = 78; console.log(i); for (var i = 0; i < 4; i++) { console.log(i); var insideloop = 100; } console.log(i);` – daniel hamidi May 12 '19 at 05:28
  • in the case of the above code, JavaScript would not have a problem with reassigning the variable with the new value. – daniel hamidi May 12 '19 at 05:30