The Loop Problem

If you’ve ever programmed in JavaScript, you’ve probably written code that looks like this:

  1. var colors = ["red", "green", "blue"];
  2. for (var i = 0, len = colors.length; i < len; i++) {
  3. console.log(colors[i]);
  4. }

This standard for loop tracks the index into the colors array with the i variable. The value of i increments each time the loop executes if i isn’t larger than the length of the array (stored in len).

While this loop is fairly straightforward, loops grow in complexity when you nest them and need to keep track of multiple variables. Additional complexity can lead to errors, and the boilerplate nature of the for loop lends itself to more errors as similar code is written in multiple places. Iterators are meant to solve that problem.