Learn / Programming / JavaScript / Iterators, Generators, Map and Set

JavaScript · Lesson 14 of 15

Iterators, Generators, Map and Set

Map, Set, symbols, iterators and generator functions.

  • Advanced
  • 15 min read
  • 3 objectives

Before this lessonLesson 13: JSON and the Fetch API

What you will learn

  • Use Map and Set
  • Write a generator
  • Make an object iterable

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 3 hours

Create a free account to keep your progress on every device.

Beyond arrays and plain objects, JavaScript has Map and Set collections and a protocol for custom iteration.

Map and Set

const seen = new Set([1, 2, 2, 3]);
seen.add(3);
console.log(seen.size, seen.has(2));
console.log([...new Set("mississippi")].join(""));

const ages = new Map();
ages.set("Ada", 36).set("Linus", 28);
console.log(ages.get("Ada"), ages.size);
for (const [name, age] of ages) console.log(name, age);
Output
3 true
misp
36 2
Ada 36
Linus 28

Use Map when keys are not strings or you add and remove often; a Set is the easy way to remove duplicates.

Generators

A generator function (function*) can pause at yield and resume later, producing values one at a time.

function* count(limit) {
  for (let i = 1; i <= limit; i++) yield i;
}
console.log([...count(4)]);

function* naturals() {
  let n = 1;
  while (true) yield n++;     // infinite, but lazy
}
const it = naturals();
console.log(it.next().value, it.next().value, it.next().value);
Output
[ 1, 2, 3, 4 ]
1 2 3

Making your own iterable

class Range {
  constructor(a, b) { this.a = a; this.b = b; }
  *[Symbol.iterator]() {
    for (let i = this.a; i <= this.b; i++) yield i;
  }
}
for (const n of new Range(1, 3)) console.log(n);
console.log(Math.max(...new Range(1, 5)));
Output
1
2
3
5
Up next · Lesson 15Testing JavaScriptUnit tests with Node's built-in runner or Jest, assertions and mocking.