Module 6: Modern JavaScript, OOP, and Data
Iterators, Generators, and Symbols
Understand the iteration protocol and when generator functions are useful.
An iterable is a value that exposes an iterator through Symbol.iterator. Arrays, strings, Maps, and Sets are common built-in iterables. The for...of loop asks an iterable for successive values.
for (const character of "JS") {
console.log(character);
}
A generator function, declared with function*, can pause at yield and resume later. Calling it returns an iterator that produces values on demand.
function* lessonNumbers() {
yield 1;
yield 2;
yield 3;
}
for (const number of lessonNumbers()) {
console.log(number);
}
Generators can help represent sequences without building a whole array in advance. They are not necessary for most simple loops, and the added abstraction should solve a real problem.
Symbols#
A Symbol creates a unique primitive value, often used as a property key to reduce naming collisions. Well-known symbols such as Symbol.iterator let objects integrate with language protocols.
const id = Symbol("id");
const record = { [id]: 123, name: "Lesson" };
console.log(record[id]);
Symbols are not a security mechanism; code that has the symbol can still access the property. Use them to model uniqueness or language integration, not to hide secrets.
Practice#
Write a generator that yields the first five positive integers. Iterate over it with for...of and explain how it differs from returning an array.