Maps and WeakMaps in JavaScript: Key Differences and Use Cases

Maps and WeakMaps in JavaScript: Key Differences and Use Cases

In JavaScript, Map and WeakMap are both collections that hold key-value pairs, but they have different behaviors and use cases. Here's a breakdown of each:

Map

  • Definition: A Map is an ordered collection of key-value pairs where keys can be of any type (including objects, functions, and primitive types).

  • Features:

    • Iteration: Maintains the order of insertion. You can iterate over its entries.

    • Size: You can easily get the number of entries using the .size property.

    • Key Types: Any value (including objects) can be used as a key.

    • Methods:

      • .set(key, value): Adds a new key-value pair.

      • .get(key): Retrieves the value associated with a key.

      • .has(key): Checks if a key exists in the map.

      • .delete(key): Removes a key-value pair.

      • .clear(): Removes all key-value pairs.

  • Use Case: Ideal when you need to associate values with keys and require ordered iteration or frequent additions/removals of key-value pairs.

// Using Map  
const myMap = new Map();  
myMap.set('name', 'Alice');  
myMap.set(1, 'One');  
console.log(myMap.get('name')); // Alice  
console.log(myMap.size); // 2

WeakMap

  • Definition: A WeakMap is similar to a Map, but it can only have objects as keys and does not prevent garbage collection of those keys.

  • Features:

    • Garbage Collection: If there are no other references to an object used as a key in a WeakMap, that key-value pair can be garbage collected. This makes WeakMap efficient in memory usage.

    • No Iteration: You cannot iterate over a WeakMap or get its size, as keys are weakly referenced.

    • Key Restrictions: Only objects (not primitives) can be used as keys.

    • Methods: Similar to Map but limited to:

      • .set(key, value)

      • .get(key)

      • .has(key)

      • .delete(key)

  • Use Case: Useful for situations where you want to associate data with an object without preventing that object from being garbage collected, such as when you want to maintain metadata about DOM elements.

Example Usage

// Using WeakMap  
const weakMap = new WeakMap();  
const obj = {};  
weakMap.set(obj, 'This is an object');  
console.log(weakMap.get(obj)); // This is an object

Summary

  • Maps: Key-value pairs, all types of keys, can be iterated, size can be checked.

  • WeakMaps: Object keys only, no iteration, garbage collection of keys when no other references exist.