12

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.

5
  • The problem with that code isn't with var, it's with the fact that you're using a for..in loop to iterate over an array, which is a bad idea. Commented Nov 10, 2016 at 2:31
  • I just wanna know let and var role in any for loop ... Can you give me a example ? Commented Nov 10, 2016 at 2:33
  • 2
    Use neither, and go for Array.forEach Commented Nov 10, 2016 at 2:35
  • @RajatSharma let create the block scope in for(in) {}, so outside the for(in) {} loop, you can't get the value of i Commented Nov 10, 2016 at 2:35
  • But use for .. in loop to array is bad usage. Commented Nov 10, 2016 at 2:36

1 Answer 1

19

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

Sign up to request clarification or add additional context in comments.

12 Comments

let create the block scope in for(in) {}, so outside the for(in) {} loop, you can't get the value of i.
Actually I am studying about "Problem with var in for loops" ... with closures function ...which is over come by let -- Can you please help me about this topic .. Thanks in advance
No one seems to care but it is bothering me and worth mentioning: for...in should not be used for collections, it is meant only for object property traversal and does not guarantee the traversal order.
@JesseRezaKhorasanee for in always need to be used with hasOwnProperty. Your question can see this: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@tomioion @DaveEveritt it's funny, the value of i on this Stack Overflow page is undefined for some reason. So if you are testing in the inspector on this page, you will not get the reference error. Swap i out for another variable name (a) and you will get the error.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.