Sitemap
Yurii Melesh

Yurii Melesh

Engineering Manager

JavaScript Iterators

3 min readOct 24, 2023

JavaScript iterators offer a standardized way to produce a sequence of values on an object. Introduced in ES6, iterators and the iterable protocol have become integral parts of the language. This blog post dives deep into JavaScript iterators, providing examples, comparisons, and insight.

1. Basics of the Iterator Protocol

An object is an iterator when it implements a next() method that returns an object with two properties:

  • value: the next value in the iteration sequence
  • done: a boolean that's true if the sequence has finished and false otherwise.
const iterator = {
current: 1,
next() {
let result = { value: this.current, done: false };
this.current++;
if (this.current > 3) result.done = true;
return result;
}
};
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3
console.log(iterator.next().done); // true
2. The Iterable ProtocolAn object is iterable if it defines its iteration method, meaning it has a property with a [Symbol.iterator] key:const iterable = {
from: 1,
to: 3,
Symbol.iterator {
return this;
},
next() {
if (this.from <= this.to) {
return { value: this.from++, done: false };
} else {
return { done: true };
}
}
};
for (let value of iterable) {
console.log(value); // 1, 2, 3
}
3. Built-in IterablesSeveral built-in JavaScript structures are iterable:
  • Arrays
  • Strings
  • Maps
  • Sets
  • etc.
Example with an array:const array = [10, 20, 30];
const arrayIterator = arraySymbol.iterator;
console.log(arrayIterator.next().value); // 10
console.log(arrayIterator.next().value); // 20
console.log(arrayIterator.next().value); // 30
4. Comparison with GeneratorsGenerators provide a simpler way to create iterators using the function* syntax and the yield keyword.function* generatorFunc() {
yield 1;
yield 2;
yield 3;
}
const gen = generatorFunc();console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
Generators are more concise, readable, and can handle complex scenarios effortlessly.

Get Yurii Melesh’s stories in your inbox

Join Medium for free to get updates from this writer.

5. Practical Use CasesIterators are beneficial in:
  • Creating custom data structures.
  • Lazy-loading elements in sequences.
  • Infinite sequences.
  • Interaction with new ES6 data structures.
6. Advanced Iteration with Spread Operator and DestructuringThe spread operator (...) and destructuring can work seamlessly with iterables, offering concise and elegant solutions for many common problems.Using the Spread Operator with IterablesYou can use the spread operator to convert any iterable into an array:const set = new Set([1, 2, 3, 4]);
const arrayFromSet = [...set];
console.log(arrayFromSet); // [1, 2, 3, 4]Destructuring and IterablesDestructuring allows you to extract values from arrays or objects and assign them to variables:const [first, second, ...rest] = "Hello";
console.log(first); // 'H'
console.log(second); // 'e'
console.log(rest); // ['l', 'l', 'o']
7. Chaining IteratorsBy making use of multiple iterators together, you can effectively chain operations to process data in sequences.Imagine a scenario where you want to filter and then map a dataset:function* filter(iterable, predicate) {
for (let value of iterable) {
if (predicate(value)) {
yield value;
}
}
}
function* map(iterable, mapper) {
for (let value of iterable) {
yield mapper(value);
}
}
const numbers = [1, 2, 3, 4, 5, 6];
const pipeline = map(filter(numbers, n => n % 2 === 0), n => n * 2);
console.log([...pipeline]); // [4, 8, 12]8. Closing IteratorsSome iterators, especially those that allocate resources (like reading from a file), might need to be closed if they're not fully consumed. The return method on an iterator is called, if present, when the loop is broken prematurely:const readingLines = {
lines: ["line 1", "line 2", "error", "line 3"],
Symbol.iterator {
let index = 0;
return {
next: () => {
if (index < this.lines.length) {
return { value: this.lines[index++], done: false };
} else {
return { done: true };
}
},
return: () => {
console.log("Exited early due to an error!");
return { done: true };
}
};
}
};
for (let line of readingLines) {
if (line === "error") break;
console.log(line);
}
In the example above, as soon as "error" is encountered, the iterator's return method is called, indicating a premature exit.ConclusionIterators in JavaScript have woven themselves into the fabric of the language, making tasks ranging from simple loops to complex data transformations elegant and maintainable. By understanding and embracing these patterns and techniques, developers can craft robust, flexible, and efficient applications. With the continuing evolution of the JavaScript language, it's more important than ever to grasp the foundational concepts, as they often serve as the base for newer features and patterns.May The 4th Be With You

--

--