Carlos Carlos - 1 month ago 9
Javascript Question

What is the different between for loop and for in loop in javascript


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>

Answer

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

Comments