I am confused with javascript let and var in for loop?

Rajat Sharma picture Rajat Sharma · Nov 10, 2016 · Viewed 9.5k times · Source

Here is my code for loop

var username = ['Sam', 'Adarsh', 'Rohit', 'Rajat'];
for(var i in username){
  console.log(username[i]);
}

it's outputing the same as needed, But I am not sure why Let declaration needed. I understand the concept of VAR and LET but not sure in which cases var create problem in for loops ?

Any body please help me to understant the concept. I am new noob and trying to figure out :)

Thanks for your help.

Answer

tomision picture tomision · Nov 10, 2016

When you use var:

var username = ['Sam', 'Adarsh', 'Rohit', 'Rajat'];
for(var i in username){
  console.log(username[i]);
}
i // 3

When you use let

var username = ['Sam', 'Adarsh', 'Rohit', 'Rajat'];
for(let i in username){
  console.log(username[i]);
}
i // Uncaught ReferenceError: i is not defined

let in ES6 will create block scope to function scope