The Iterator Protocol
An object is iterable if it implements Symbol.iterator. The method must return an object with a next() method yielding { value, done }.
const range = {
start: 1,
end: 5,
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next() {
if (current <= end) {
return { value: current++, done: false };
}
return { value: undefined, done: true };
}
};
}
};
for (const num of range) {
console.log(num);
}
Try it Yourself →
Custom Iterables
Create iterable objects representing any sequence — like Fibonacci numbers, custom collections, or infinite sequences.
const fibonacci = {
[Symbol.iterator]() {
let a = 0, b = 1;
return {
next() {
const value = a;
a = b;
b = value + b;
if (value > 50) return { done: true };
return { value, done: false };
}
};
}
};
for (const num of fibonacci) {
console.log(num);
}
Try it Yourself →
Built-in Iterables
Arrays, Strings, Maps, Sets, and NodeLists are built-in iterables. You can use for...of on all of them.
const str = "Hello";
for (const char of str) {
console.log(char);
}
const map = new Map([["a", 1], ["b", 2]]);
for (const [key, value] of map) {
console.log(key + ":", value);
}
Try it Yourself →