What you'll learn
Map and Set make intent clearer than improvised arrays or objects, while iterator protocols let any data source participate in for...of and lazy pipelines.
By the end of this lesson, you'll be able to:
- Select the right collection
- Explain iterable and iterator protocols
- Create a lazy generator
Core mental model
Use this decision table as a compact reference. Focus on what each tool means and when it earns its place in production code.
| Concept | What it means | Decision rule |
|---|---|---|
| Map | Key-value collection with keys of any type | Use for dynamic dictionaries and frequent keyed operations |
| Set | Collection of unique values | Use for membership and deduplication |
| Generator | Function that pauses and yields values lazily | Use for sequences that should not be built eagerly |
Professional workflow
Build the behavior in small, observable steps. Each step should leave something you can inspect or test.
- Describe the collection and iteration protocol boundary: inputs, outputs, state, timing, and expected failures.
- Implement the smallest correct path with names that expose intent.
- Add edge cases and failure handling before introducing abstractions.
- Verify behavior with realistic data and one deliberately adversarial example.
- Refactor only after the observable behavior is protected.
Make behavior observable
Guided code lab
Count with Map and deduplicate with Set
The collections express lookup and uniqueness directly.
const tags = ["js", "web", "js", "node"];
const unique = new Set(tags);
const counts = new Map();
for (const tag of tags) counts.set(tag, (counts.get(tag) ?? 0) + 1);
console.log([...unique].join(", "));
console.log(counts.get("js"));Generate a bounded sequence lazily
The generator computes each value only when the consumer asks for it.
function* range(start, end) {
for (let value = start; value <= end; value += 1) yield value;
}
console.log([...range(3, 6)]);Production practice
Contract
A custom iterable must return an iterator whose next method yields {value, done} records.
Verification
Test empty, duplicate, object-key, early-break, and exhausted-iterator cases.
Operations
Use WeakMap or WeakSet only when weak reachability semantics are actually required.
Common failure mode
Independent workshop
Create a lazy paginated-record iterable and a Set-backed selection model.
Your finished workshop must include:
- A custom generator
- Early termination without loading all pages
- Map-based metadata keyed by record ID
Definition of done
Recap & quick check
Key takeaways
- Map models key-value lookup
- Set models uniqueness
- Iterables work with for...of
- Generators produce values lazily
Quick check
1. Which collection guarantees unique values?
2. What keyword yields a generator value?
3. Can a Map use an object as a key?
Keep the workshop. Later modules deliberately build on these decisions, so each exercise can become part of your final portfolio architecture.