You are used to the classic way of iterating through an array:

var data = [ 'a', 'b', 'c' ];
for(var i=0; i<data.length; i++) {
    console.log(data[i]);
}
// a, b, c

But you ran into a different way of looping in someone else’s code:

for(var item in data) {
    console.log(data[item];
}

What does this for .. in expression do? Does it work the exact same way as the classic for? Well, the truth is .. not really! This expresion loops through the enumerable properties of an object. Now, since Arrays are also objects, it’s true that you can use for .. in to loop through an array, but there are a few gotchas you need to be aware of.

“for .. in” will also iterate over any non-numeric properties that have been assigned

var data = ['a', 'b', 'c'];
data.foo = 'bar';
for(var item in data) {
	console.log(data[item]);
}
// a, b, c, bar

“for .. in” will only return the populated items of the array

var data = ['a', 'b', 'c' ];
data[4] = 'd';
for(var i=0; i<data.length; i++) {
	console.log(i + ' ' + data[i]);
}
// 0 - a, 1 - b, 2 - c, 3 - undefined, 4 - d
for(var item in data) {
	console.log(item + ' ' + data[item]);
}
// 0 - a, 1 - b, 2 - c, 4 - d

“for .. in” will also iterate over the properties that have been assigned somewhere up in the prototype chain

Array.prototype.sum = function() { };
var data = ['a', 'b', 'c'];
for(var item in data) {
	console.log(item + ' ' + data[item]);
}
// 0 - a, 1 - b, 2 - c, sum - function() { }

Comments