Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
An iterator is an object that implements the iterator protocol with a next() method. It returns { value, done } to control iteration!
next() method that returns:{ value: any, done: boolean }// Create iterator manually
function createIterator(arr) {
let index = 0;
return {
next() {
if (index < arr.length) {
return {
value: arr[index++],
done: false
};
}
return { done: true };
}
};
}
const iter = createIterator([1, 2, 3]);
console.log(iter.next()); // { value: 1, done: false }
console.log(iter.next()); // { value: 2, done: false }
console.log(iter.next()); // { value: 3, done: false }
console.log(iter.next()); // { done: true }// Use with while loop
const iterator = createIterator([10, 20, 30]);
let result = iterator.next();
while (!result.done) {
console.log(result.value);
result = iterator.next();
}
// Output: 10 20 30
// Or consume all at once
function toArray(iterator) {
const arr = [];
let result = iterator.next();
while (!result.done) {
arr.push(result.value);
result = iterator.next();
}
return arr;
}Different iterator implementations
// Make object iterable
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
if (current <= last) {
return { value: current++, done: false };
}
return { done: true };
}
};
}
};
// Now works with for...of!
for (const num of range) {
console.log(num); // 1 2 3 4 5
}
// And spread operator
console.log([...range]); // [1, 2, 3, 4, 5]
// And destructuring
const [first, second, ...rest] = range;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]Make any object iterable with Symbol.iterator
Building reusable iterator utilities
Iterate through paginated data
Object with next() method
Returns { value, done }
Object with [Symbol.iterator]()
Works with for...of, spread, destructuring
Values computed on demand
Perfect for infinite sequences
Build utilities: map, filter, take
Chain operations efficiently