Iterable and iterator contracts
Quick answer
An iterable supplies an iterator through Symbol.iterator. An iterator advances through next(), returning an object with value and done.
How it works
An iterable may create a fresh iterator for each traversal. Store the cursor inside that iterator, not on the shared iterable if repeatable independent traversals are intended. for...of and array spread obtain an iterator and repeatedly call its next method until done is truthy. A returned primitive is an invalid iterator result. An iterator is itself iterable only if it implements Symbol.iterator, commonly returning itself.
const r={ [Symbol.iterator](){let i=1;return {next(){return i<=3?{value:i++,done:false}:{done:true};}};} }; console.log(JSON.stringify([...r]),JSON.stringify([...r]));Expected output in Node.js:
[1,2,3] [1,2,3]Each traversal creates its own cursor.
const it=["a","b"][Symbol.iterator](); console.log(it[Symbol.iterator]()===it,it.next().value);Expected output in Node.js:
true aThe built-in array iterator is self-iterable and advances.
Common mistakes
An object with next alone is not necessarily spreadable. Avoid sharing a single cursor when two independent traversals are required.
Practice
Implement a repeatable iterable for the integers from 1 to n and traverse it twice.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Iterable and iterator contracts — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which member obtains an iterator from an iterable?
Where should a repeatable range store independent cursor state?
What must a synchronous next call return?
What is the exact console output in Iterable and iterator contracts example 1?
const r={ [Symbol.iterator](){let i=1;return {next(){return i<=3?{value:i++,done:false}:{done:true};}};} }; console.log(JSON.stringify([...r]),JSON.stringify([...r]));What is the exact console output in Iterable and iterator contracts example 2?
const it=["a","b"][Symbol.iterator](); console.log(it[Symbol.iterator]()===it,it.next().value);