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.
var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted.
Use map() instead of for() loops map() function works. If you only have knowledge of for() loops in JavaScript, this article will require you to understand the Arrow Function Expression syntax (a.k.a. “fat arrow” functions).
Use var , it reduces the scope of the variable otherwise the variable looks up to the nearest closure searching for a var statement. If it cannot find a var then it is global (if you are in a strict mode, using strict , global variables throw an error).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With