Map and Set in JavaScript

Introduction

Map and Set are built-in collection types for key-value pairs and unique values. They handle keys and membership more cleanly than plain objects and arrays in many cases—especially non-string keys, frequent add/delete, and deduplication. This chapter starts the JavaScript standard library track after OOP.

Prerequisites

Set — Unique Values

javascript
// Duplicates ignored
const tags = new Set(["js", "web", "js", "api"]);
tags.add("node");
 
console.log(tags.size);
console.log(tags.has("web"));
 
for (const tag of tags) {
  console.log(tag);
}

Convert array → unique list:

javascript
// Dedupe with Set
const ids = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(ids)];
console.log(unique);

Map — Key-Value with Any Key Type

javascript
// Object keys, numbers, strings as keys
const cache = new Map();
 
cache.set({ id: 1 }, "payload-a");
cache.set("session", "abc123");
cache.set(42, "answer");
 
console.log(cache.get("session"));
console.log(cache.size);

Iteration:

javascript
// entries, keys, values
for (const [key, value] of cache) {
  console.log(key, value);
}

Map vs Plain Object

Use casePrefer
JSON-like record with string keysObject literal
Keys are not strings, or keys change oftenMap
Need .size and clear iteration orderMap
Need prototype-free dictionaryMap

WeakMap and WeakSet (Brief)

Hold weak references—keys can be garbage-collected when no other references exist. Common for private metadata on DOM nodes or caches tied to object lifetime—not needed for most beginner exercises.

Map from Object

javascript
// Object.entries → Map
const config = { host: "localhost", port: 3000 };
const map = new Map(Object.entries(config));
 
console.log(map.get("port"));

Mini Example: Count Word Frequencies

javascript
// Map as frequency table
function wordCounts(text) {
  const counts = new Map();
  const words = text.toLowerCase().split(/\s+/);
 
  for (const word of words) {
    counts.set(word, (counts.get(word) ?? 0) + 1);
  }
 
  return counts;
}
 
const counts = wordCounts("js is fun and js is popular");
console.log(counts.get("js"));

FAQ

Is Set ordered?

Insertion order is preserved when iterating—like Map.

Can I use objects as Set elements?

Yes—uniqueness is by reference, like ===.

map[key] vs map.get(key)?

Always use get/set on Map—bracket syntax does not use Map’s internal storage.

What comes next?

Date and time.