Given a simple zero based, numerically indexed array:
var list = ['Foo', 'Bar', 'Baz'];
Many times, I have noticed that when someone suggests looping through variables in an array like this:
for(var item in list) { ... }
...there's almost certainly someone suggesting that that's bad practice and suggests an alternative approach:
var count = list.length; for(var i = 0; i < count; i++) { var item = list[i]; ... }
What's the reasoning for not using the simpler version above and to use the second example instead?
Using for (var property in array) will cause array to be iterated over as an object, traversing the object prototype chain and ultimately performing slower than an index-based for loop. for (... in ...) is not guaranteed to return the object properties in sequential order, as one might expect.
It is considered bad practice to use a for in loop in general and it should be avoided as much as possible. There are cases where it can't be avoid for instance if you are iterating though a JSON object, but this doesn't happen as often and generally you shouldn't be extending these types.
For Loop to Traverse Arrays. We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.
In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.
First, the order of the loop is undefined for a for...in
loop, so there's no guarantee the properties will be iterated in the order you want.
Second, for...in
iterates over all enumerable properties of an object, including those inherited from its prototype. In the case of arrays, this could affect you if your code or any library included in your page has augmented the prototype of Array
, which can be a genuinely useful thing to do:
Array.prototype.remove = function(val) { // Irrelevant implementation details }; var a = ["a", "b", "c"]; for (var i in a) { console.log(i); } // Logs 0, 1, 2, "remove" (though not necessarily in that order)
Speed?
for(..;..;..)
loop proved to be 36 times faster than for .. in
when I tested it here.
Link courtesy this SO answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With