Re: difference between 'for (var i=0; i < x.length; i++)' and 'for (var i in x)'



erdibalint wrote:
Hi,

I've come across the problem and I spent a remarkable amount of time
debugging at the end of which I found the cause of the bug to be the
following:

var arr = ['a', 'b', 'c', 'd'];
var arr2 = [];
for (var i=0; i < arr.length; i++) {
var elt = arr[i];
arr2.push(elt);
}
// arr2 equals ["a", "b", "c", "d"]

var arr = ['a', 'b', 'c', 'd'];
var arr2 = [];
for (var i in arr) {
var elt = arr[i];
arr2.push(elt);
}
// arr2 equals ["a", "b", "c", "d", function()]

I thought that the second type of for loop is identical to the first
one and just adds syntetic sugar. I guess I was wrong, can anyone shed
some light on how the two loops are different?

"syntactic sugar"?

The first loops over the indexes of arr, from 0 to (arr.length - 1).

The second loops over the enumerable properties of arr, which, for an unmodified Array and where Array.prototype remains unmodified, will be those index[1] properties that have been assigned a value.

However, if either the array object itself (arr) or Array.prototype have been modified with additional properties that aren't indexes, the second will also loop over those also whereas the first will not.

A for..in loop is typically only used for sparse arrays, i.e. where the length is large but only a few values have been assigned to some indexes, where it is significantly faster than iterating over all the indexes from 0 to length-1.

Some libraries extend Array.prototype and some script authors treat array objects as "hashes". Both of which may cause for..in loops to do unexpected things that otherwise they may not.


1. An array index is just a property that has an integer as its property name, although the index is still a string.


--
Rob
"We shall not cease from exploration, and the end of all our
exploring will be to arrive where we started and know the
place for the first time." -- T. S. Eliot
.