Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 823
Rajat Sharma Avatar asked Nov 10 '16 02:11

Rajat Sharma


People also ask

What is the difference between LET and VAR in for loop?

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.

What can I use instead of for loop in JavaScript?

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).

Can we use VAR in for loop in JavaScript?

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).


1 Answers

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

like image 139
tomision Avatar answered Oct 03 '22 22:10

tomision