Map, Set, WeakMap & WeakSet

Move beyond standard Objects and Arrays. Learn how to store unique values with Sets and map complex keys with Maps.

JavaScript8 min readConcept 28 of 62

Advanced Data Structures

While Arrays and Objects are the workhorses of JavaScript, ES6 introduced four new collection types for specialized tasks: Map, Set, WeakMap, and WeakSet.

Unlike Arrays (which are ordered lists) or Objects (which map strings to values), these structures offer unique memory and iteration constraints.

Set (Unique Values)

A Set is a collection of values where every item must be **completely unique**. If you attempt to .add() a value that already exists, the Set simply ignores it.

Because Sets enforce uniqueness, they are the fastest and easiest way to remove duplicates from an array: const unique = [...new Set([1, 1, 2])].

Map (Any Key Type)

A Map is a key-value store similar to an Object. However, standard Objects only allow strings or Symbols as keys. A Map allows **anything** to be a key - including functions, arrays, or other objects!

Maps also preserve insertion order perfectly and have a built-in .size property, making them much easier to iterate over than standard Objects.

Collection Architecture

Examine the structural differences between an Object, a Map, and a Set to understand when to use each.

Collection Architecture

// 1. Set: Unique Values
const arr = [1, 1, 2, 3, 3];
const unique = new Set(arr);
// 2. Map: Complex Keys
const metadata = new Map();
const domNode = document.querySelector('#btn');
metadata.set(domNode, 'Clicked 5 times');
Set (Uniqueness)
Input Array
1
1
2
3
3
X Drop
Result Set
1
2
3
Map (Complex Keys)
Key (Any Type)
Value
<button> (Object)
=>
"Clicked 5x"
() => {} (Func)
=>
"Handler"
[1, 2] (Array)
=>
true
Unlike Objects, Maps allow ANY data type to act as the key!
iUse a Set when you need a list of unique values (like filtering duplicate IDs). Use a Map when you need to attach metadata to complex objects (like DOM nodes) without mutating them directly.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the primary difference between a Map and a standard Object?
  2. 2How many items will this Set contain? `new Set([1, 2, 2, 3, 1])`
  3. 3Why would you use a WeakMap instead of a standard Map?

Remember this

  • Set is a collection of unique values. It automatically ignores duplicates.
  • Passing an array into new Set(arr) is the easiest way to deduplicate it.
  • Map is a key-value store that allows ANY data type to be used as a key (even objects).
  • Maps preserve insertion order and provide a direct .size property.
  • WeakMap and WeakSet prevent memory leaks by allowing their contents to be garbage collected.

Done with this concept?

Mark it complete to track your progress. No login needed.