2

Possible Duplicate:
JavaScript for…in vs for

I am using a for loop in my function. I use both type of loops, "for in" and "for". Both are producing the same result so I want to know what is the difference between these loops and how to know which loop should be used.

<script type="text/javascript">
var jam = ['amit','sam','ram','soly']
for(var i in jam){
alert(jam[i])
}
//for (i=0; i<jam.length; i++) {
//  jam[i]
//alert(jam[i].length)
//}
</script>
</head>
<body>
</body>
Community
  • 1
  • 1
Carlos
  • 6,805
  • 22
  • 83
  • 171

3 Answers3

2

you can use whichever you understood clearly. for arrays you can use both the cases.

for arrays you can use

for (var i = 0; i < a.length; i++){
  //do something
}

for objects you can use

for ( var i in obj){
  //do something
}

as you cannot get the length of object.

Shreedhar
  • 5,084
  • 3
  • 19
  • 27
2

It depends on what you need. I usually use for-in loop because it is a shorter form, but sometimes you may want to have control over the iteration variable. For instance, if you want to iterate over even indices, you'd need to use the normal for loop:

for (var i = 0; i < myarray.length; i+=2) {...}

The same applies, for example, if you want to iterate backwards:

for (var i = myarray.length-1; i >= 0; i--) {...}

Certainly, for objects, the for-in loop allows you to get the property name in the iteration variable. For example:

var myobject = {year: 1992, city: "Barcelona"}
for (var propname in myobject) alert(propname + " = " + myobject[propname]);

In your example, I'd use for-in because you are doing a simple iteration. Moreover I think in a non-optimized Javascript compiler/interpreter, the for-in loop would be even faster because variable increment is done internally (i.e. it is not a Javascript statement such as "i++").

Claudix
  • 4,755
  • 13
  • 27
  • Some variable that has been assigned to an object key value outside the for-loop could not be found inside this loop, therefore I would recommend to use for-in-loop in that case. – Frontend employee Feb 02 '18 at 15:17
2

for loops are meant to iterate while incrementing/decrementing.

// note that I'm making this big and ugly to show what's going on
var incrementor = 1, length = 10,
    array = [ "one", "two", "three", "four", "five",
              "six", "seven", "eight", "nine", "ten" ];

for (; incrementor <= length; incrementor = incrementor + 1) {
    console.log(incrementor);  // 1,2,3,...,10
    console.log( array[incrementor - 1] );  // "one", "two", "three", ..., "ten"
}

for ... in ... loops are meant to enumerate through object properties.

var object = { "key1" : "one", "key2" : "two", "key3" : "three" },
    key = "";

for (key in object) {
    console.log(key); // "key1", "key2", "key3"
    console.log( object[key] ); // "one", "two", "three"
}

The reason you use for for arrays is because on bad browsers, for ... in ... can include not only the number properties (ie: key=0, key=1,...), but it can also enumerate through things you don't want it to... ...like key=splice, key=length, key=unshift. Not really a good thing if you're running this code on a professional site, or for specialized versions of JS being run on specific hardware, or being run as a scripting language in a program like Unity or Unreal Editor's UnrealScript.

The reason you don't use an iterator on objects is because you don't normally make objects like:

var obj = { "0" : "zero", "1" : "one", "2" : "two" };

And even if you did (jQuery does something like this, for example), there might be word-based properties that you want to enumerate over, but you can't, because you're counting.

Also important to note: enumerating with for ... in ... isn't standardized in its functionality. What this means is that it's not 100% guaranteed to spit the values out in the order you're expecting them in. If you're relying on your loop going 0,1,2,3,... then for ... in ... can't guarantee that 100% of the browsers will do it that way, 100% of the time - even if most browsers get it right most of the time.

Most-frequently, they go by the first-in, first-out rule, now. If you build your object like { one : 1, two : 2, three : 3 }, any modern browser will print 1,2,3. If you build your object like: { two: 2, one: 1, six: 6 }, you'll get 2,1,6.

But that's a 95% of the time "should", not a 100% of the time "will".

Norguard
  • 24,349
  • 4
  • 38
  • 45