Programs are built to process data, and the patterns used to iterate over that data greatly affect readability. The iterator pattern provides a standardized way to consume data one piece at a time, rather than all at once.
An iterator is a data structure that references a source and exposes a next() method. Each call to next() returns an object with value and done properties. Iteration continues until done becomes true.
ES6 introduced the for..of loop for consuming iterators:
for (let val of it) {
console.log(`Iterator value: ${val}`);
}This loop is cleaner and more readable than manual iteration.
The ... operator also consumes iterators — either into arrays or function arguments:
var vals = [ ...it ];
doSomethingUseful(...it);In both cases, the iterator is fully consumed and its values are spread into the target context.
An iterable is a value that can be iterated over. Each time it’s consumed, a new iterator instance is created. Built-in iterables in JS include arrays, strings, maps, sets, and more.
var arr = [10, 20, 30];
for (let val of arr) {
console.log(`Array value: ${val}`);
}
var greeting = "Hello world!";
var chars = [ ...greeting ];
// ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]Maps iterate over entries — key/value pairs:
for (let [btn, btnName] of buttonNames) {
btn.addEventListener("click", () => {
console.log(`Clicked ${btnName}`);
});
}You can use keys(), values(), or entries() to control what gets iterated:
for (let btnName of buttonNames.values()) {
console.log(btnName);
}
for (let [idx, val] of arr.entries()) {
console.log(`[${idx}]: ${val}`);
}By following the iteration protocol, you can make your own data structures compatible with for..of and .... This leads to more readable and consistent code across your application.
Iteration in JavaScript is standardized through the iterator protocol and built-in iterable structures. Using for..of and the spread operator makes data consumption intuitive and clean. Understanding and applying these patterns is essential for writing modern, maintainable JS code.