7Iterators and Generators

WHAT'S IN THIS CHAPTER?

  • Introduction to iteration
  • The iterator pattern
  • Generators

WROX.COM DOWNLOADS FOR THIS CHAPTER

Please note that all the code examples for this chapter are available as a part of this chapter’s code download on the book's website at www.wrox.com/go/projavascript4e on the Download Code tab.

The term “iteration” is derived from the Latin itero, meaning “repeat” or “do again.” In the context of software, “iteration” means repetitively performing a procedure multiple times, in sequence, and usually with an expectation of termination. The ECMAScript 6 specification introduces two high-level features—iterators and generators—to allow for cleaner, faster, and easier iteration.

INTRODUCTION TO ITERATION

In JavaScript, one of the simplest examples of iteration is a counting loop:

for (let i = 1; i <= 10; ++i) {
 console.log(i);
}

Loops are a fundamental iterative tool because they allow you to specify how many iterations should occur and what should occur during each iteration. Each loop iteration will finish execution before another begins, and the order in which each iteration occurs is well-defined.

Iteration can occur over ordered collections of items. (Consider “ordered” in this context to imply there is an accepted sequence in which all the items should be traversed, with a definitive beginning and end item.) In JavaScript, the most common example of this ordered collection is an array.

let collection = ['foo', 'bar', 'baz']; ...

Get Professional JavaScript for Web Developers, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.