How to iterate over an array

JavaScript polyfill, by , Friday, March 7th, 2014

Iterating over an array in JavaScript is as easy as in most other languages; you simply use a normal for-loop like this;

  1. // Some array arr
  2. var arr = ['mango', 'durian', 'dragon fruit'],
  3. i;
  4.  
  5. // Iterating over arr with a for-loop
  6. for (i = 0; i < arr.length; i += 1) {
  7. // Logging the array elements to the browser console
  8. console.log(arr[i];
  9. }

This is fairly simple, but there are some things to be aware of. Even though arrays in JavaScript are objects with special abilities, you should not iterate over them using a for-in loop like you would with an object. There are a few reasons for this, the first being that it is simply misguiding. Someone else editing your code, or yourself editing your own code later on, might fall into believing that you are dealing with an object and not an array. This could potentially lead to problems. The second reason is, that using a for-in loop on an array, does not work as you might expect. Take a look at the following code;

  1. // Some array arr initialized with two values. arr[0] = 'a' and arr[1] = 'b'
  2. var arr = ['a', 'b'];
  3.  
  4. // Now we assign the string 'd' to arr[3]
  5. arr[3] = 'd';
  6.  
  7. // Iterating over arr with a for-loop gives us;
  8. // 0 : a
  9. // 1 : b
  10. // 2 : undefined
  11. // 3 : d
  12. for (var i = 0; i < arr.length; i += 1) {
  13. console.log(i + ' : ' + arr[i]);
  14. }
  15.  
  16. // Iterating over the same array arr with a for-in loop gives us;
  17. // 0 : a
  18. // 1 : b
  19. // 3 : d
  20. for (var key in arr) {
  21. console.log(key + ' : ' + arr[key]);
  22. }

Now you might be lured into thinking that the for-in loop is doing the better job, as it leaves out the undefined slots in the array, but it is not quite so. What you are iterating over with the for-loop, is the elements in the array, while what you are iterating over with the for-in loop, are properties of the array, which includes anything added to Array.prototype. So in short, always loop over an array with a for-loop.