7Iterators and Generators
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 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'];
for (let index ...
Get Professional JavaScript for Web Developers, 5th 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.