forEach
var people = ["Bob", "Jane", "Mary", "Chris"];
for(var person in people) {
processPerson( person );
}
This is a very common pattern and ES5 introduces a new Array function, Array.prototype.forEach to make this really easy:
Using forEach makes this code a little shorter, but there are other more important reasons why it is often a better choice.
- You don’t have to write the array iteration logic yourself, which means fewer opportunities for bugs, and in this case less chance of an accidental off-by-one error or incorrect length calculation.
- forEach handles arrays with empty elements automatically, skipping those indexes that don’t have values.
- Putting the body of the loop into a function ensures that any variables defined will only be in scope within the loop body, reducing the risk of loop variables conflicting with other variables in your code.
for
for(var i = 0; i < people.length; i++) {
processPerson(people[i]);
}
If so, you’ve probably noticed that for..in loops give you the indexes of the elements in the array, not the elements themselves.