Module 5: Arrays, Objects, and Collections
Map, Set, WeakMap, and WeakSet
Choose collection types for key-value mappings, uniqueness, and object-associated data.
Objects are useful for records, but Map and Set provide different collection semantics.
A Map stores key-value pairs and can use values of many types as keys. A Set stores unique values.
const visits = new Map();
visits.set("home", 10);
visits.set("learn", 25);
console.log(visits.get("learn")); // 25
const uniqueTopics = new Set(["JavaScript", "Java", "JavaScript"]);
console.log([...uniqueTopics]); // ["JavaScript", "Java"]
Maps preserve insertion order and expose size, get, set, has, and delete. Sets expose add, has, and delete. They are often clearer than using plain objects for arbitrary user-supplied keys or tracking unique values.
Weak collections#
WeakMap and WeakSet hold weak references to object keys/values where supported by their respective semantics. They are non-enumerable, so you cannot loop over all their entries. They are useful in specialized cases such as attaching metadata to objects without keeping those objects alive solely through the collection.
Which should you choose?#
- Use an object for a record with known property names.
- Use a
Mapfor a collection of key-value pairs with dynamic keys. - Use a
Setwhen uniqueness matters. - Use weak collections when their garbage-collection behaviour is part of the design.
Practice#
Remove duplicates from an array using Set, then use a Map to count how often each tag appears.