Phase 2 · Core JavaScriptModule 15~46 min read

Collections, Iterators & Generators

Go beyond arrays with Map, Set, iterable protocols, and lazy generator sequences.

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.

ConceptWhat it meansDecision rule
MapKey-value collection with keys of any typeUse for dynamic dictionaries and frequent keyed operations
SetCollection of unique valuesUse for membership and deduplication
GeneratorFunction that pauses and yields values lazilyUse 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.

  1. Describe the collection and iteration protocol boundary: inputs, outputs, state, timing, and expected failures.
  2. Implement the smallest correct path with names that expose intent.
  3. Add edge cases and failure handling before introducing abstractions.
  4. Verify behavior with realistic data and one deliberately adversarial example.
  5. Refactor only after the observable behavior is protected.

Make behavior observable

Before optimizing or abstracting, make inputs, outputs, state changes, timing, and failure paths visible. JavaScript becomes much easier to reason about when hidden work is exposed.

Guided code lab

Count with Map and deduplicate with Set

The collections express lookup and uniqueness directly.

collections.js
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.

generator.js
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

Weak collections are not enumerable; they are not drop-in privacy-focused replacements for Map and Set.

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

Demonstrate the happy path and at least two edge cases, keep responsibilities separated, and add a short note explaining one design choice.

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.