JavaScript for impatient programmers (beta)
Please support this book: buy it or donate
(Ad, please don’t block.)

31. WeakMaps (WeakMap)



WeakMaps are similar to Maps, with the following differences:

The next two sections examine in more detail what that means.

31.1. Attaching values to objects via WeakMaps

This is how you attach a value to an object via a WeakMap:

const wm = new WeakMap();
{
  const obj = {};
  wm.set(obj, 'attachedValue'); // (A)
}
// (B)

In line A, we attach a value to obj. In line B, obj can be garbage-collected. The notable feature of WeakMaps is that wm does not prevent obj from being garbage-collected. This technique of attaching a value to an object is equivalent to storing a property of that object externally. If wm were a property, the previous code would look as follows.

{
  const obj = {};
  obj.wm = 'attachedValue';
}

31.1.1. The keys of a WeakMap are weakly held

The keys of a WeakMap are said to be weakly held: Normally, references to an object prevent the object from being garbage-collected. However, WeakMap keys don’t. Additionally, WeakMap entries, whose keys were garbage-collected, are also (eventually) garbage-collected.

Weakly held keys only make sense for objects. Thus, you can only use objects as keys:

> const wm = new WeakMap();
> wm.set(123, 'test')
TypeError: Invalid value used as weak map key

31.2. WeakMaps as black boxes

It is impossible to inspect what’s inside a WeakMap:

These restrictions enable a security property. Quoting Mark Miller: “The mapping from weakmap/key pair value can only be observed or affected by someone who has both the weakmap and the key. With clear(), someone with only the WeakMap would’ve been able to affect the WeakMap-and-key-to-value mapping.”

31.3. Examples

31.3.1. Caching computed results via WeakMaps

With WeakMaps, you can associate previously computed results with objects, without having to worry about memory management. The following function countOwnKeys() is an example: it caches previous results in the WeakMap cache.

const cache = new WeakMap();
function countOwnKeys(obj) {
  if (cache.has(obj)) {
    return [cache.get(obj), 'cached'];
  } else {
    const count = Object.keys(obj).length;
    cache.set(obj, count);
    return [count, 'computed'];
  }
}

If we use this function with an object obj, you can see that the result is only computed for the first invocation, while a cached value is used for the second invocation:

> const obj = { foo: 1, bar: 2};

> countOwnKeys(obj)
[2, 'computed']
> countOwnKeys(obj)
[2, 'cached']

31.3.2. Keeping private data via WeakMaps

In the following code, the WeakMaps _counter and _action are used to store the data of virtual properties of instances of Countdown:

let _counter = new WeakMap();
let _action = new WeakMap();

class Countdown {
  constructor(counter, action) {
    _counter.set(this, counter);
    _action.set(this, action);
  }
  dec() {
    let counter = _counter.get(this);
    if (counter < 1) return;
    counter--;
    _counter.set(this, counter);
    if (counter === 0) {
      _action.get(this)();
    }
  }
}

// The two pseudo-properties are truly private:
assert.deepEqual(
  Reflect.ownKeys(new Countdown()),
  []);

  Exercise: WeakMaps for private data

exercises/maps-sets/weakmaps_private_data_test.js

31.4. WeakMap API

The constructor and the four methods of WeakMap work the same as their Map equivalents:

  Quiz

See quiz app.