We've been using for...of to loop over arrays, strings, Maps, and Sets. We've also used the spread operator [...] on all of them.
But try the same thing with a plain object:
const user = { name: "Rahul", age: 21 };
for (const item of user) {
console.log(item);
}JavaScript throws:
TypeError: user is not iterableSo what makes an array "iterable" but not a plain object? The answer is a small set of rules called the iteration protocol. Once you understand it, you can make your own objects work with for...of, and you'll understand generators, one of JavaScript's most interesting features.
Iterables and Iterators
There are two related ideas, and their names are easy to mix up:
An iterable is an object that can be looped over. An iterator is the object that actually does the looping, handing out one value at a time.
Think of a playlist and a music player:
Iterable → the playlist (the collection of songs)
Iterator → the player that remembers which song is next
next() → pressing the "next song" buttonArrays, strings, Maps, Sets, and a few other built-ins are iterable. Plain objects are not.
The Iteration Protocol
Here are the rules, step by step:
An iterable has a method stored under the special key
Symbol.iterator.Calling that method returns an iterator.
An iterator is any object with a
next()method.Each call to
next()returns an object of the form{ value, done }.When there are no more values,
doneistrue.
Symbol.iterator is a built-in symbol (a unique, special property key) that JavaScript reserves for exactly this purpose.
Let's drive an array's iterator by hand:
const colors = ["red", "green", "blue"];
const iterator = colors[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());Output:
{ value: 'red', done: false }
{ value: 'green', done: false }
{ value: 'blue', done: false }
{ value: undefined, done: true }This is exactly what for...of does behind the scenes:
for (const color of colors) { ... }
1. iterator = colors[Symbol.iterator]()
2. result = iterator.next()
3. if result.done is true → stop
4. color = result.value, run the loop body
5. go back to step 2Making Your Own Iterable
Let's build a range object that produces numbers from from to to. All we need is a [Symbol.iterator]() method that returns an object with next():
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 { value: undefined, done: true };
}
};
}
};
for (const n of range) {
console.log(n);
}
console.log([...range]);Output:
1
2
3
4
5
[ 1, 2, 3, 4, 5 ]Our object now works with for...of and spread, just like an array. Notice that current lives in a closure (from the closures chapter), so each new loop gets its own fresh counter.
What Works with Iterables?
Any iterable, built-in or your own, works with all of these:
Feature | Example |
|---|---|
|
|
Spread operator |
|
Array destructuring |
|
|
|
|
|
const range = {
from: 1,
to: 4,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next: () => current <= last
? { value: current++, done: false }
: { value: undefined, done: true }
};
}
};
const [first, second] = range;
console.log(first, second);
console.log(Math.max(...range));
console.log(new Set(range).has(3));Output:
1 2
4
trueIterators Are Used Up
An iterator only moves forward. Once it reaches the end, it stays finished:
const letters = ["a", "b", "c"];
const it = letters[Symbol.iterator]();
console.log([...it]);
console.log([...it]);Output:
[ 'a', 'b', 'c' ]
[]The second spread got nothing because the iterator was already exhausted. The array itself is fine: calling letters[Symbol.iterator]() again gives a brand new iterator. This is also true for the iterators returned by map.keys(), map.entries(), and set.values() that we saw in the previous chapter.
What is a Generator?
Writing iterators by hand works, but it's a lot of code: an object, a next() method, and { value, done } objects. Generators do all of that for us.
A generator function is a special function that can pause in the middle of running and resume later. It is written with
function*and usesyieldto hand out values one at a time.
function* countToThree() {
yield 1;
yield 2;
yield 3;
}
const gen = countToThree();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());Output:
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: undefined, done: true }Look familiar? A generator object is an iterator. It follows the same protocol automatically.
How a Generator Runs, Step by Step
The key thing to understand is that calling a generator function does not run its body. It just creates a paused generator object. The body runs bit by bit, each time you call next():
function* steps() {
console.log("Start");
yield "A";
console.log("Middle");
yield "B";
console.log("End");
}
const gen = steps();
console.log("Generator created");
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().done);Output:
Generator created
Start
A
Middle
B
End
trueHere's the timeline:
steps() → nothing runs, body is paused at the very top
next() #1 → runs "Start", pauses at yield "A" → returns { value: "A", done: false }
next() #2 → runs "Middle", pauses at yield "B" → returns { value: "B", done: false }
next() #3 → runs "End", reaches the end → returns { value: undefined, done: true }A normal function runs from top to bottom in one go. A generator runs until the next yield, remembers exactly where it stopped (including its local variables), and continues from there next time.
Generators Make Iterables Easy
Generator objects are also iterable, so you can use them directly with for...of and spread:
function* range(from, to, step = 1) {
for (let i = from; i <= to; i += step) {
yield i;
}
}
for (const n of range(1, 5)) {
console.log(n);
}
console.log([...range(0, 20, 5)]);Output:
1
2
3
4
5
[ 0, 5, 10, 15, 20 ]Compare this with our hand-written range object earlier. Same behaviour, a fraction of the code.
We can also use a generator as the [Symbol.iterator] method of an object or class (the * goes before the method name):
class Playlist {
constructor(...songs) {
this.songs = songs;
}
*[Symbol.iterator]() {
for (const song of this.songs) {
yield `Now playing: ${song}`;
}
}
}
const myList = new Playlist("Kesariya", "Believer", "Naatu Naatu");
for (const line of myList) {
console.log(line);
}Output:
Now playing: Kesariya
Now playing: Believer
Now playing: Naatu NaatuLazy and Infinite Sequences
Generators are lazy: they only compute a value when someone asks for it. That means a generator can describe an infinite sequence without running out of memory.
function* idGenerator(prefix) {
let id = 1;
while (true) {
yield `${prefix}-${id++}`;
}
}
const orderIds = idGenerator("ORD");
console.log(orderIds.next().value);
console.log(orderIds.next().value);
console.log(orderIds.next().value);Output:
ORD-1
ORD-2
ORD-3The while (true) loop is safe here because the generator pauses at every yield. It only runs when we call next().
Never spread or
for...ofan infinite generator without a way to stop.[...idGenerator("ORD")]would run forever and eventually crash.
Stopping Early with break
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const result = [];
for (const n of fibonacci()) {
if (n > 50) break;
result.push(n);
}
console.log(result.join(", "));Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34Iterator Helpers (ES2025)
Since ES2025, iterators (including generator objects and the iterators from map.keys(), set.values(), etc.) have their own map(), filter(), take(), drop(), toArray(), and more. They're available in all modern browsers and Node.js 22+.
Unlike array methods, they are lazy, so they work even on infinite sequences:
function* naturals() {
let n = 1;
while (true) yield n++;
}
const firstFiveEvenSquares = naturals()
.filter(n => n % 2 === 0)
.map(n => n * n)
.take(5)
.toArray();
console.log(firstFiveEvenSquares);Output:
[ 4, 16, 36, 64, 100 ]Only the numbers 1 to 10 were ever generated, because take(5) stopped asking for more after five results. With arrays, you would have to build the whole array first.
yield*: Delegating to Another Iterable
yield* hands out every value of another iterable (or generator), one by one:
function* vowels() {
yield "a";
yield "e";
}
function* letters() {
yield* vowels();
yield* ["x", "y"];
yield "z";
}
console.log([...letters()]);Output:
[ 'a', 'e', 'x', 'y', 'z' ]This is handy for combining generators or walking nested structures like trees. For example, flattening a nested array of any depth:
function* flatten(arr) {
for (const item of arr) {
if (Array.isArray(item)) {
yield* flatten(item);
} else {
yield item;
}
}
}
console.log([...flatten([1, [2, [3, [4]], 5]])]);Output:
[ 1, 2, 3, 4, 5 ]Sending Values into a Generator
yield works in both directions. The value you pass to next(value) becomes the result of the yield expression where the generator was paused:
function* conversation() {
const name = yield "What is your name?";
const city = yield `Hi ${name}! Which city are you from?`;
return `${name} lives in ${city}.`;
}
const chat = conversation();
console.log(chat.next().value);
console.log(chat.next("Priya").value);
console.log(chat.next("Pune"));Output:
What is your name?
Hi Priya! Which city are you from?
{ value: 'Priya lives in Pune.', done: true }A few details to notice:
The first
next()just starts the generator. There's no pausedyieldyet to receive a value, so anything passed to the firstnext()is ignored.A
returnvalue appears withdone: true. However,for...ofand spread ignore the returned value; they only collect yielded values.
You won't need two-way generators often, but this pausing-and-resuming idea is the foundation that async/await is conceptually built on, as you'll see in later chapters.
Normal Function vs Generator Function
Normal function | Generator function |
|---|---|
|
|
Runs its body immediately when called | Returns a paused generator object; body runs on |
Runs to completion in one go | Pauses at each |
Returns one value | Can produce many values over time |
Can be an arrow function | Cannot be an arrow function (there's no arrow syntax for generators) |
Common Mistakes
1. Forgetting the *
function numbers() {
yield 1; // ❌ SyntaxError
}yield only has its special meaning inside a function*. In a normal function, JavaScript can't make sense of it and reports a SyntaxError before the code even runs.
2. Expecting the body to run when you call the function
function* greet() {
console.log("Hello!");
}
greet(); // prints nothing
greet().next(); // prints "Hello!"3. Reusing a finished generator
function* abc() {
yield "a";
yield "b";
}
const gen = abc();
console.log([...gen]);
console.log([...gen]); // already finished
console.log([...abc()]); // call the function again for a fresh oneOutput:
[ 'a', 'b' ]
[]
[ 'a', 'b' ]4. Trying to for...of a plain object
Plain objects aren't iterable. Loop over Object.keys(obj), Object.values(obj), or Object.entries(obj) instead (these return arrays), or convert the object to a Map.
Interview Tips
Iterable vs iterator: an iterable has
[Symbol.iterator](); an iterator hasnext()returning{ value, done }.Why are generators useful? Lazy evaluation, infinite sequences, simple custom iterables, and processing large data piece by piece without loading it all into memory.
What does calling a generator function return? A generator object, which is both an iterator and an iterable. The body hasn't started yet.
Is a generator object reusable? No. Once done, it stays done.
Practice ideas:
Write a generator
take(iterable, n)that yields only the firstnvalues.Write a generator that yields all prime numbers, and print the first 10.
Make a
LinkedListclass iterable with*[Symbol.iterator]().Write a generator
chunk(array, size)that yields sub-arrays of lengthsize.
Conclusion
The iteration protocol is what powers for...of, spread, destructuring, and Array.from():
Iterable → has [Symbol.iterator]() which returns an iterator
Iterator → has next() which returns { value, done }Generators are the easy way to create iterators:
function* gen() {
yield 1; // pause here and hand out 1
yield 2; // pause here and hand out 2
}They run lazily, pause at every yield, remember their state, and can even represent infinite sequences. Keep this idea of a function that can pause and resume in mind. It will come back when we study asynchronous JavaScript and async/await.