Search code examples
javascriptfor-loopscopevarlet

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


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.


Solution

  • 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