The Loop Problem
If you’ve ever programmed in JavaScript, you’ve probably written code that looks like this:
var colors = ["red", "green", "blue"];
for (var i = 0, len = colors.length; i < len; i++) {
console.log(colors[i]);
}
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.