# WeakMap and WeakSet

`WeakMap` and `WeakSet` are special data structures in JavaScript (introduced in ES6) that behave similarly to `Map` and `Set`, but with one crucial difference: they hold "weak" references to their keys (WeakMap) or values (WeakSet).

## 1. WeakMap

A `WeakMap` is a collection of key/value pairs where the **keys must be objects** and the values can be arbitrary values.

### Key Features
1.  **Weak References:** The references to the key objects are held "weakly". If there are no other references to the key object, it can be garbage collected.
2.  **Keys must be Objects:** You cannot use primitive values (string, number, boolean) as keys.
3.  **Not Iterable:** You cannot loop over a WeakMap (`forEach`, `for...of`) or get its size (`.size`). This is because the garbage collector decides when to remove items, so the state is non-deterministic.

### Syntax

```javascript
let weakMap = new WeakMap();
let obj = { name: "Object" };

weakMap.set(obj, "some value");

console.log(weakMap.get(obj)); // "some value"

obj = null; 
// The object is now eligible for garbage collection.
// Once collected, the entry in weakMap is automatically removed.
```

### Use Case: Private Data
Before private class fields (`#field`), WeakMaps were used to store private data for objects without exposing it or causing memory leaks.

```javascript
const privateData = new WeakMap();

class User {
  constructor(name) {
    privateData.set(this, { name: name });
  }

  getName() {
    return privateData.get(this).name;
  }
}
```

## 2. WeakSet

A `WeakSet` is a collection of objects, similar to `Set`, but the objects are held weakly.

### Key Features
1.  **Weak References:** Objects in the set can be garbage collected if there are no other references to them.
2.  **Values must be Objects:** You cannot store primitives.
3.  **Not Iterable:** No `size`, `forEach`, etc.

### Syntax

```javascript
let weakSet = new WeakSet();
let obj = { data: 1 };

weakSet.add(obj);
console.log(weakSet.has(obj)); // true

obj = null;
// obj is removed from weakSet automatically when GC runs.
```

## 3. Summary Differences

| Feature | Map / Set | WeakMap / WeakSet |
| :--- | :--- | :--- |
| **Keys/Values** | Any type (primitives & objects) | **Objects only** |
| **References** | Strong (prevents GC) | **Weak** (allows GC) |
| **Iterable** | Yes (`keys()`, `values()`, loop) | **No** |
| **Size property** | Yes (`.size`) | **No** |

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/es6-features]]
[[programming/javascript/vanilla/data-types]]