Mastering ES6 - WeakMap and WeakSet
Published: 2023-09-08 12:13:58

## Introduction

ES6 (ECMAScript 2015) introduced the WeakMap and WeakSet data structures, which are used for handling object references in a memory-efficient manner. They are similar to Map and Set but have distinct characteristics that make them useful in specific scenarios. In this guide, we'll explore WeakMap and WeakSet, their characteristics, and how to use them effectively in JavaScript.

## WeakMap

A WeakMap is a collection of key-value pairs where the keys must be objects, and the values can be of any type. Unlike a regular Map, a WeakMap's key references are weak, meaning they do not prevent the garbage collector from removing the key and its associated value when there are no other references to them. This makes WeakMaps useful in scenarios where you want to associate data with objects without preventing those objects from being garbage collected.

### Creating a WeakMap

```javascript
const weakMap = new WeakMap();
```

### Methods and Usage

- `set(key, value)`: Adds a new key-value pair to the WeakMap.
- `get(key)`: Retrieves the value associated with the given key.
- `has(key)`: Checks if a key exists in the WeakMap.
- `delete(key)`: Removes the key-value pair associated with the given key.

```javascript
const person = { name: "Alice" };
const weakMap = new WeakMap();

weakMap.set(person, 30); // Associate age 30 with the person object

console.log(weakMap.has(person)); // true
console.log(weakMap.get(person)); // 30

weakMap.delete(person); // Remove the key-value pair
```

## WeakSet

A WeakSet is a collection of objects where each object can only occur once in the set. Similar to WeakMap, the references to objects in a WeakSet are weak, meaning they do not prevent the garbage collector from removing the objects when there are no other references to them.

### Creating a WeakSet

```javascript
const weakSet = new WeakSet();
```

### Methods and Usage

- `add(value)`: Adds a new object to the WeakSet.
- `has(value)`: Checks if an object exists in the WeakSet.
- `delete(value)`: Removes an object from the WeakSet.

```javascript
const obj1 = { id: 1 };
const obj2 = { id: 2 };
const weakSet = new WeakSet();

weakSet.add(obj1);
weakSet.add(obj2);

console.log(weakSet.has(obj1)); // true

weakSet.delete(obj1); // Remove obj1 from the WeakSet
```

## Use Cases

- **Caching Data**: WeakMaps can be used to associate cached data with objects. When an object is no longer needed, its associated cache data can be automatically removed by the garbage collector.

- **Preventing Memory Leaks**: WeakSets can be used to hold references to objects in a way that prevents memory leaks. For example, in event handling, you can use a WeakSet to keep track of event listeners associated with DOM elements. When an element is removed from the DOM, the reference in the WeakSet will be automatically cleaned up.

- **Private Data**: WeakMaps can be used to store private data associated with objects. Since the data is stored in a WeakMap, it can't be easily accessed from outside the object.

## Conclusion

WeakMap and WeakSet are valuable additions to JavaScript for handling object references in a memory-efficient and safe manner. They are particularly useful when dealing with scenarios where you want to associate data with objects while allowing those objects to be garbage collected when they are no longer in use. Understanding the differences between WeakMap, WeakSet, Map, and Set can help you choose the right data structure for your specific use case in ES6.