Iteration Protocol
Iteration Protocol
Section titled “Iteration Protocol”Introduction
Section titled “Introduction”The iteration protocol consists of two parts: iterable and iterator. An iterable is any object with a Symbol.iterator method. Calling that method returns an iterator — an object with a next() method.
The Protocol
Section titled “The Protocol”// An iterable has Symbol.iterator methodconst iterable = [1, 2, 3];
// Get the iteratorconst iterator = iterable[Symbol.iterator]();
// Call next() to get valuesconsole.log(iterator.next()); // { value: 1, done: false }console.log(iterator.next()); // { value: 2, done: false }console.log(iterator.next()); // { value: 3, done: false }console.log(iterator.next()); // { value: undefined, done: true }The next() Method
Section titled “The next() Method”Each call to next() returns an object with two properties:
value: the current value in the sequencedone:falseif more values remain,trueif the sequence is complete
Built-in Iterables
Section titled “Built-in Iterables”// Arraysfor (const item of [1, 2, 3]) console.log(item);
// Stringsfor (const char of 'hello') console.log(char);
// Mapsfor (const [key, value] of new Map([['a', 1]])) {}
// Setsfor (const value of new Set([1, 2, 3])) {}
// Arguments (array-like)function demo() { for (const arg of arguments) console.log(arg);}
// Typed Arrays, NodeLists, etc.Using the Spread Operator
Section titled “Using the Spread Operator”The spread operator (...) also uses the iteration protocol:
const str = 'hello';const chars = [...str]; // ['h', 'e', 'l', 'l', 'o']
const set = new Set([1, 2, 3]);const arr = [...set]; // [1, 2, 3]
const map = new Map([['a', 1], ['b', 2]]);const entries = [...map]; // [['a', 1], ['b', 2]]Destructuring with Iterables
Section titled “Destructuring with Iterables”const [a, b, c] = [1, 2, 3]; // works via iteration protocolconst [first, ...rest] = 'hello';console.log(first); // 'h'console.log(rest); // ['e', 'l', 'l', 'o']Summary
Section titled “Summary”- Iterable: object with
Symbol.iteratormethod - Iterator: object with
next()returning{ value, done } for...ofconsumes any iterable- Spread operator (
...) uses the iteration protocol - Arrays, Strings, Maps, Sets are built-in iterables