Pages

Best Practices: Iterating over Arrays

  • A simple for loop (see for):
    for (var i=0; i<arr.length; i++) {
        console.log(arr[i]);
    }
  • One of the array iteration methods (see Iteration (Nondestructive)). For example,forEach():
    arr.forEach(function (elem) {
        console.log(elem);
    });
Do not use the for-in loop (see for-in) to iterate over arrays. It iterates over indices, not over values. And it includes the keys of normal properties while doing so, including inherited ones.

http://speakingjs.com/es5/ch18.html