Map vs WeakMap in JavaScript1

Maps and WeakMaps are both collection objects in JavaScript, but they have important differences in how they handle

  • keys,
  • memory management, and
  • available operations.

Map

A Map is a collection of key-value pairs where keys can be of any type (objects, primitive values, functions).

// Creating a Map
const map = new Map();
 
// Setting key-value pairs
map.set('name', 'John');
map.set({id: 1}, 'Object as key');
map.set(function() {}, 'Function as key');
 
// Getting values
console.log(map.get('name')); // 'John'
 
// Checking if a key exists
console.log(map.has('name')); // true
 
// Size property
console.log(map.size); // 3
 
// Iteration
map.forEach((value, key) => {
  console.log(key, value);
});
 
// Deleting entries
map.delete('name');
 
// Clearing the map
map.clear();

WeakMap

A WeakMap is also a collection of key-value pairs, but with some important restrictions:

// Creating a WeakMap
const weakMap = new WeakMap();
 
// Keys must be objects
const obj1 = {};
const obj2 = {};
 
// Setting key-value pairs
weakMap.set(obj1, 'Value for obj1');
weakMap.set(obj2, 'Value for obj2');
 
// Getting values
console.log(weakMap.get(obj1)); // 'Value for obj1'
 
// Checking if a key exists
console.log(weakMap.has(obj1)); // true
 
// Deleting entries
weakMap.delete(obj1);
 
// This would throw an error - primitive values can't be keys
// weakMap.set('string', 'value');
 
// No size property, no iteration methods
// console.log(weakMap.size); // undefined
// weakMap.forEach() - doesn't exist

Key Differences

  1. Key Types:
  2. Map: Can use any value as a key (objects, primitives, functions)
  3. WeakMap: Can only use objects as keys (not primitives)
  4. Memory Management:
  5. Map: Maintains strong references to its keys, preventing garbage collection
  6. WeakMap: Holds “weak” references to keys, allowing them to be garbage collected if no other references exist
  7. Available Methods:
  8. Map: Has size property, clear() method, and supports iteration (forEach, entries, keys, values)
  9. WeakMap: Only has get(), set(), has(), and delete() methods
  10. Enumeration:
  11. Map: Keys and values can be enumerated
  12. WeakMap: Cannot enumerate keys or values (no forEach, keys, values, or entries methods)

When to Use Each

Use Map when:

  • You need to store primitive values as keys
  • You need to know the size of the map
  • You need to iterate over the entries
  • You need to clear all entries at once

Use WeakMap when:

  • You need to associate data with objects without preventing garbage collection
  • You want to avoid memory leaks in long-running applications
  • You’re implementing private object properties or caching

WeakMaps are particularly useful for scenarios where you want to attach metadata to objects without interfering with garbage collection, making them ideal for certain caching implementations and maintaining private data.

Footnotes

  1. This text was generated using v0 ↩