sets and maps

An array answers “give me the third item” A Set answers “have I seen this before” A Map answers “what belongs to this key”

Set

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

Output:

3
true

Adding the same value twice does nothing That makes de-duplication a one liner: [...new Set(items)]

Map

const record = new Map([["host", "local"], ["port", 443]]);
console.log(record.get("port"));

Output:

443

Object keys are strings or symbols Map keys can be any value Use Map when the key is an object or when the collection grows and shrinks often

Choosing

  • array for ordered work
  • Set for membership and uniqueness
  • Map for a dictionary with non string keys

Next

Objects and state in 07 objects

Posted