11

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.

Rajat Sharma
  • 135
  • 1
  • 2
  • 11

1 Answers1

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

tomision
  • 964
  • 9
  • 22
  • 1
    `let` create the block scope in `for(in) {}`, so outside the `for(in) {}` loop, you can't get the value of `i`. – tomision Nov 10 '16 at 02:35
  • 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 – Rajat Sharma Nov 10 '16 at 02:49
  • @RajatSharma the main point is **closures** not the `for in`.http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1 this answer tell me clearly: what is closure. – tomision Nov 10 '16 at 03:23
  • Using `let i in username` has drastic performance issues with respect to `let i = 0; i < username.length; i++` – Thomas Wagenaar Jul 02 '17 at 19:01
  • 2
    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. – TomSlick Oct 13 '17 at 19:07
  • Does anyone have a link where I can investigate further why 'for ... in' should not be used for collections? – Jesse Reza Khorasanee Jul 12 '19 at 08:45
  • 1
    @JesseRezaKhorasanee `for in` always need to be used with `hasOwnProperty`. Your question can see this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in – tomision Jul 12 '19 at 09:53
  • the second example actually *doesn't* produce `Uncaught ReferenceError: i is not defined` - it works fine… – Dave Everitt Jan 29 '20 at 10:13
  • @DaveEveritt you run second example in browser? – tomision Jan 31 '20 at 07:49
  • Yes, I did in a simple html5 page – Dave Everitt Jan 31 '20 at 22:41
  • @DaveEveritt You can try in nodejs – tomision Feb 01 '20 at 07:21
  • 1
    @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. – Corey Mar 01 '20 at 02:34