Do you think there is a big difference in for...in and for loops? What kind of \"for\" do you prefer to use and why?
Let\'s say we have an array of associative array
Use the Array().forEach loop to take advantage of parallelism
Douglas Crockford recommends in JavaScript: The Good Parts (page 24) to avoid using the for in
statement.
If you use for in
to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.
Everything but the properties can be filtered out with .hasOwnProperty
. This code sample does what you probably wanted originally:
for (var name in obj) {
if (Object.prototype.hasOwnProperty.call(obj, name)) {
// DO STUFF
}
}
Using forEach to skip the prototype chain
Just a quick addendum to @nailer's answer above, using forEach with Object.keys means you can avoid iterating over the prototype chain without having to use hasOwnProperty.
var Base = function () {
this.coming = "hey";
};
var Sub = function () {
this.leaving = "bye";
};
Sub.prototype = new Base();
var tst = new Sub();
for (var i in tst) {
console.log(tst.hasOwnProperty(i) + i + tst[i]);
}
Object.keys(tst).forEach(function (val) {
console.log(val + tst[val]);
});
I second opinions that you should choose the iteration method according to your need. I would suggest you actually not to ever loop through native Array
with for in
structure. It is way slower and, as Chase Seibert pointed at the moment ago, not compatible with Prototype framework.
There is an excellent benchmark on different looping styles that you absolutely should take a look at if you work with JavaScript. Do not do early optimizations, but you should keep that stuff somewhere in the back of your head.
I would use for in
to get all properties of an object, which is especially useful when debugging your scripts. For example, I like to have this line handy when I explore unfamiliar object:
l = ''; for (m in obj) { l += m + ' => ' + obj[m] + '\n' } console.log(l);
It dumps content of the whole object (together with method bodies) to my Firebug log. Very handy.
There is an important difference between both. The for-in iterates over the properties of an object, so when the case is an array it will not only iterate over its elements but also over the "remove" function it has.
for (var i = 0; i < myArray.length; i++) {
console.log(i)
}
//Output
0
1
for (var i in myArray) {
console.log(i)
}
// Output
0
1
remove
You could use the for-in with an if(myArray.hasOwnProperty(i))
. Still, when iterating over arrays I always prefer to avoid this and just use the for(;;) statement.
for(;;) is for Arrays : [20,55,33]
for..in is for Objects : {x:20,y:55:z:33}