Loading...
Loading...
Specialized collections for unique values and key-value pairs.
Beyond the basics lie the tools professional JavaScript relies on daily: Promises for async work, classes for object-oriented design, Map and Set for specialized collections, and structured error handling for reliable applications.
Learn Map, Set & WeakMap in JavaScript — covering Map, Set, WeakMap & WeakSet, When to Use What with interactive visual examples and step-by-step explanations.
Once you are comfortable with functions and data structures, the next step is the patterns professional codebases use every day. Promises coordinate asynchronous work, classes organize related behavior, and try/catch keeps applications from crashing on unexpected input.
This module bridges beginner syntax and production-ready JavaScript. You will learn when to reach for Map instead of a plain object, how Set eliminates duplicates, and how error handling turns fragile scripts into reliable software.
Understanding map, set & weakmap is essential for every JavaScript developer. It shows up in frontend UI code, backend APIs, and framework internals — and getting it wrong leads to bugs that are hard to trace. This chapter builds intuition with visuals so the behavior sticks.
Key-value pairs. Any type as a key.
const map = new Map(); map.set("name", "Ada"); map.set(42, "answer"); map.set(true, "yes"); map.get("name"); // "Ada" map.get(42); // "answer" map.size; // 3
Unlike objects, Map keys can be any type — numbers, booleans, objects, even functions.
Unique values only. No duplicates.
const set = new Set([1, 2, 3, 2, 1]); // Set {1, 2, 3} — duplicates removed! set.add(4); // Set {1, 2, 3, 4} set.add(2); // Set {1, 2, 3, 4} — no change set.size; // 4
Set automatically deduplicates. Adding an existing value is a no-op.
Garbage-collector friendly. Keys must be objects.
// WeakMap: keys are weakly held const cache = new WeakMap(); let obj = { data: "important" }; cache.set(obj, "cached result"); obj = null; // obj is garbage-collected! // cache entry automatically removed // Use cases: // • Private data for class instances // • Caching without memory leaks // • DOM node metadata
WeakMap/WeakSet don't prevent garbage collection. Perfect for metadata you don't want to leak memory.
Choose the right collection.
Common questions about map, set & weakmap.