Iterators & Iterables
Published by Brayan K
Every time you write for…of, spread an array with [...items], or destructure values, a hidden protocol is doing the work. That protocol is the iteration protocol, built on Symbol.iterator.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Separate the collection from the cursor that walks it
An iterable provides a method at Symbol.iterator that returns an iterator. The iterator has a next method that produces result objects. Think of the collection and its current traversal position as separate responsibilities: obtaining an iterator does not mean you have copied all its values.
const items = ["A17", "B24"];
// Ask the iterable for one traversal cursor.
const iterator = items[Symbol.iterator]();
const first = iterator.next();
console.log(first.value, first.done);
// Each next call advances this cursor, not every iterator over items.
const second = iterator.next();
console.log(second.value, second.done);
const finished = iterator.next();
console.log(finished.value, finished.done);
console.log(items.length);
// ✅ Expected output:
// A17 false
// B24 false
// undefined true
// 2For...of obtains an iterator, repeatedly calls next and tests completion. Loops & Iteration owns loop syntax; this lesson explains the objects that supply the values.
Calling next does not make an object iterable
A manually usable iterator only needs the iterator contract. For...of and array spread first ask for Symbol.iterator. An object with next but no iterable method therefore cannot be spread just because you can advance it manually.
const cursor = {
next() {
return { value: "A17", done: false };
}
};
console.log(cursor.next().value);
console.log([...cursor]);
// ✅ Expected output:
// A17
// ✅ Expected error:
// TypeError: cursor is not iterableconst values = ["A17", "B24"];
let index = 0;
const cursor = {
next() {
if (index >= values.length) return { done: true };
return { value: values[index++], done: false };
},
[Symbol.iterator]() {
return this;
}
};
console.log(cursor[Symbol.iterator]() === cursor);
console.log(cursor.next().value);
console.log(JSON.stringify([...cursor]));
console.log(JSON.stringify([...cursor]));
// ✅ Expected output:
// true
// A17
// ["B24"]
// []Returning this makes the cursor usable by iteration syntax, but it does not reset its state. The second spread starts from the cursor’s existing position. Built-in array iterators likewise return themselves from Symbol.iterator.
Completion is decided by done, not by the value
Next must return an object. A truthy done marks completion; a missing or false-looking done means a value is available. An undefined value can be a real yielded value, and a value carried with done true is not emitted by for...of. Prefer explicit boolean done fields in your own code.
const source = {
[Symbol.iterator]() {
let step = 0;
return {
next() {
step += 1;
if (step === 1) return { value: undefined, done: false };
return { value: "completion note", done: true };
}
};
}
};
let visits = 0;
for (const value of source) {
visits += 1;
console.log(value === undefined);
}
console.log(visits);
// ✅ Expected output:
// true
// 1const source = {
[Symbol.iterator]() {
let sent = false;
return {
next() {
if (sent) return { done: true };
sent = true;
return { value: "A17" };
}
};
}
};
console.log(JSON.stringify([...source]));
// ✅ Expected output:
// ["A17"]const broken = {
[Symbol.iterator]() {
return { next() { return 7; } };
}
};
console.log([...broken]);
// ✅ Expected error:
// TypeError: Iterator result 7 is not an objectThis is a protocol error, not a rule that every result must contain both property names. A completion result can simply be an object with done true. Once a well-behaved iterator finishes, subsequent next calls should keep reporting completion.
A fresh iterator needs fresh traversal state
A reusable iterable creates a new cursor for each Symbol.iterator call. Put its position inside that method. Putting the position outside would make separate readers consume one shared cursor instead.
const shelf = {
items: ["A17", "B24"],
[Symbol.iterator]() {
const items = this.items;
let index = 0;
return {
next() {
if (index >= items.length) return { done: true };
return { value: items[index++], done: false };
}
};
}
};
const firstReader = shelf[Symbol.iterator]();
const secondReader = shelf[Symbol.iterator]();
console.log(firstReader.next().value, firstReader.next().value);
console.log(secondReader.next().value);
console.log(JSON.stringify([...shelf]));
console.log(JSON.stringify([...shelf]));
// ✅ Expected output:
// A17 B24
// A17
// ["A17","B24"]
// ["A17","B24"]The iterable supplies the fresh cursor; the language does not promise that every Symbol.iterator call creates one. The one-use cursor above deliberately returns itself. Generators (function*, yield) owns generator objects and their consumption rules.
An array-like object is a different contract
Having numbered properties and length does not supply Symbol.iterator. Array.from can also read an array-like object, so successful conversion with Array.from is not proof that for...of or array spread will work.
const arrayLike = { 0: "A17", 1: "B24", length: 2 };
console.log([...arrayLike]);
// ✅ Expected error:
// TypeError: arrayLike is not iterableconst arrayLike = { 0: "A17", 1: "B24", length: 2 };
console.log(typeof arrayLike[Symbol.iterator]);
console.log(JSON.stringify(Array.from(arrayLike)));
const record = { first: "A17", second: "B24" };
console.log(JSON.stringify(Object.values(record)));
// ✅ Expected output:
// undefined
// ["A17","B24"]
// ["A17","B24"]For ordinary records, choose whether you mean keys, values or entries rather than expecting automatic iteration. Object spread has its own property-copying contract, explained in Spread & Rest Operators.
Early exit can close an iterator through return
For...of calls an iterator’s optional return method when the loop exits early, such as through break. A short array destructuring pattern can also finish early and close its iterator. Normal exhaustion does not call return. This is one reason a handwritten next loop is not a complete replacement for for...of.
function source() {
let index = 0;
return {
[Symbol.iterator]() { return this; },
next() {
if (index >= 2) return { done: true };
return { value: ++index, done: false };
},
return() {
index = 2;
console.log("closed");
return { done: true };
}
};
}
console.log("break");
for (const value of source()) {
console.log(value);
break;
}
console.log("full");
for (const value of source()) console.log(value);
console.log("one binding");
const [first] = source();
console.log(first);
// ✅ Expected output:
// break
// 1
// closed
// full
// 1
// 2
// one binding
// closed
// 1This custom return both records cleanup and marks its cursor finished. Not all iterators have return. An array iterator can be resumed after a break because that early exit does not itself reset or exhaust it.
const cursor = ["A17", "B24", "C31"].values();
for (const value of cursor) {
console.log(value);
break;
}
console.log(typeof cursor.return);
console.log(JSON.stringify([...cursor]));
// ✅ Expected output:
// A17
// undefined
// ["B24","C31"]When your iterator owns a resource, its cleanup design needs to account for early exits and failures. Generators (function*, yield) owns generator finally blocks; this example only demonstrates the protocol hook.
Producing on demand does not make unlimited consumption safe
A custom iterator can calculate one value per next call without first building an array. But array spread and Array.from ask for the entire sequence. They can allocate a large result, or never finish if the iterator never reports completion. Keep demonstration consumers bounded.
let current = 0;
const cursor = {
next() {
if (current >= 1000000) return { done: true };
return { value: current++, done: false };
}
};
console.log(cursor.next().value);
console.log(cursor.next().value);
console.log("values requested", current);
// ✅ Expected output:
// 0
// 1
// values requested 2This cursor stores its position rather than a prebuilt million-item array. That is a description of this implementation, not a measured byte count or a guarantee about every iterable. String iteration similarly follows its own contract: it produces code points, not necessarily complete user-perceived characters; Strings & String Methods owns that text distinction.
Complete a reusable two-value iterable
Supply the iterator method name and the not-finished flag using the literal hints. The cursor position belongs inside Symbol.iterator so a second traversal starts independently.
const items = {
[Symbol.iterator]() {
let index = 0;
const values = ["A17", "B24"];
return {
___() {
if (index >= values.length) return { done: true };
return { value: values[index++], done: ___ };
}
};
}
};
// 👉 replace ___ with next
// 👉 replace ___ with false
console.log(JSON.stringify([...items]));
console.log(JSON.stringify([...items]));
// ✅ Expected output:
// ["A17","B24"]
// ["A17","B24"]Design a finite range with a clear progress rule
Write range(start, end, step) as a reusable iterable of ascending numbers, including end only when a step lands on it. Accept safe-integer bounds and a positive safe-integer step; reject invalid arguments with RangeError. A start above end produces no values. Check a stepped range twice, an empty range and a zero-step failure. Each traversal must own its current value.
function range(start, end, step) {
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) ||
!Number.isSafeInteger(step) || step <= 0) {
throw new RangeError("Use safe integers and a positive step");
}
return {
[Symbol.iterator]() {
let current = start;
return {
next() {
if (current > end) return { done: true };
const value = current;
current += step;
return { value, done: false };
}
};
}
};
}
const values = range(2, 7, 2);
console.log(JSON.stringify([...values]));
console.log(JSON.stringify([...values]));
console.log(JSON.stringify([...range(5, 2, 1)]));
try {
range(1, 3, 0);
} catch (error) {
console.log(error.name + ": " + error.message);
}
// ✅ Expected output:
// [2,4,6]
// [2,4,6]
// []
// RangeError: Use safe integers and a positive stepA zero step would never move the cursor toward completion. This contract deliberately supports ascending ranges only; accepting negative steps would require a different boundary test. Numbers & Math owns safe-integer checks and numeric representation.
References: MDN iteration protocols, for...of and Array.from.
Practice quiz
What does this complete program print? const iterator = ["A17", "B24"].values(); console.log(iterator.next().value); console.log(JSON.stringify([...iterator]));
- A17 ["B24"]
- A17 ["A17","B24"]
- B24 ["A17"]
- A17 []
Answer: A17 ["B24"]. The manual next consumes the first value, so spread collects the remaining value.
What does this complete program print? const iterator = ["A17"].values(); console.log(iterator[Symbol.iterator]() === iterator); console.log(JSON.stringify([...iterator])); console.log(JSON.stringify([...iterator]));
- false ["A17"] ["A17"]
- true ["A17"] []
- true ["A17"] ["A17"]
- false ["A17"] []
Answer: true ["A17"] []. An array iterator returns itself and is not reset by a later spread.
Which error ends this program? const source = { [Symbol.iterator]() { return { next() { return 7; } }; } }; console.log([...source]);
- TypeError: source is not iterable
- ReferenceError: next is not defined
- TypeError: Iterator result 7 is not an object
- RangeError: Invalid array length
Answer: TypeError: Iterator result 7 is not an object. The iterable method exists, but next returns a primitive instead of a result object.
What does this complete program print? const arrayLike = { 0: "A17", length: 1 }; console.log(typeof arrayLike[Symbol.iterator]); console.log(JSON.stringify(Array.from(arrayLike)));
- function ["A17"]
- undefined []
- object ["A17"]
- undefined ["A17"]
Answer: undefined ["A17"]. Array.from can use indexed properties and length when no iterator is present.
What does this complete program print? const source = { [Symbol.iterator]() { return { next() { return { value: 9, done: true }; } }; } }; console.log(JSON.stringify([...source]));
- []
- [9]
- [true]
- [null]
Answer: []. A completion value is not emitted as an element by spread.
What does this complete program print? const items = ["A17", "B24"]; const first = items.values(); const second = items.values(); first.next(); console.log(second.next().value, first.next().value);
- B24 B24
- A17 B24
- A17 A17
- B24 A17
Answer: A17 B24. Each new array iterator has its own traversal position.
What does this complete program print? let closed = 0; const source = { [Symbol.iterator]() { return this; }, next() { return { value: 1, done: false }; }, return() { closed++; return { done: true }; } }; for (const value of source) break; console.log(closed);
- 0
- 2
- 1
- undefined
Answer: 1. Early break calls the iterator’s available return hook once.
What does this complete program print? const iterator = ["A17", "B24"].values(); for (const value of iterator) break; console.log(JSON.stringify([...iterator]));
- ["A17","B24"]
- []
- ["A17"]
- ["B24"]
Answer: ["B24"]. The first value is consumed, and this array iterator has no return hook that closes it.
Continue this course
- Previous: Callbacks & Callback Hell
- Next: Generators (function*, yield) — Pause and resume functions to produce values on demand
- Quick reference: JavaScript cheat sheet