Javascript - Collection WeakMap

Introduction

A WeakMap is a Map in which the keys are weakly referenced.

A WeakMap doesn't prevent its keys from being garbage collected if all references to the key are lost and there are no more references to the value.

You don't need to worry about memory leaks with WeakMaps.

WeakMap does not support entries(), keys(), values(), forEach(), and clear() methods.

In WeakMap, every key must be an object.

We can't iterate over the WeakMap collection and we can't get the length of the collection.

A WeakMap only has four methods:

  • delete(key)
  • has(key)
  • get(key)
  • set(key, value)

Example

let wMap = new WeakMap(); 

wMap.set('a', 'b'); 
// Uncaught TypeError: Invalid value used as weak map key 

const o1 = {}, 
      o2 = () => {}, 
      o3 = window; 

wMap.set(o1, 42); 
wMap.set(o2, "hello"); 
wMap.set(o3, undefined); 

wMap.get(o3); // undefined, because that is the set value 
wMap.has(o1); // true 
wMap.delete(o1); 
wMap.has(o1); // false