Iterators and Iterables
Iterators and Iterables are protocols that define how to iterate over a collection of data in JavaScript. They provide a standardized way to traverse data structures.
1. Iterables
An object is iterable if it implements the Iterable Protocol. This means it has a method keyed by Symbol.iterator.
- This method must return an Iterator.
- Built-in iterables:
String,Array,Map,Set,TypedArray,arguments,NodeList.
2. Iterators
An object is an iterator if it implements the Iterator Protocol. This means it has a next() method that returns an object with two properties:
value: The next value in the iteration sequence.done: A boolean indicating if the sequence has finished (trueif finished).
3. How they work together
When you use a for...of loop:
- It calls the object's
Symbol.iteratormethod to get the iterator. - It calls
iterator.next()repeatedly. - It stops when
done: true.
const array = [1, 2];
const iterator = array[Symbol.iterator]();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
4. Creating a Custom Iterable
You can make your own objects iterable by implementing [Symbol.iterator].
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
let current = this.from;
let last = this.to;
return {
next() {
if (current <= last) {
return { done: false, value: current++ };
} else {
return { done: true };
}
}
};
}
};
for (let num of range) {
console.log(num); // 1, 2, 3, 4, 5
}
5. Generators
Generators are the easiest way to create iterators. A generator function (function*) automatically returns a Generator object, which is both an iterable and an iterator.
programming/javascript/vanilla/javascript programming/javascript/vanilla/generators programming/javascript/vanilla/es6-features