JS: WeakMap

By Xah Lee. Date: . Last updated: .

What is weakmap

WeakMap is similar to the Map Object, with 3 exceptions:

  1. Keys can only be Object Type, or unregistered Symbol type (meaning, symbols user created, not builtin symbols.).
  2. If a object in the key is not used elsewehere in your program, or no longer used, that key entry is deleted automatically.
  3. Weakmap cannot be iterated over, nor get its keys, nor looped over, nor get its item count, nor clear all.

Methods for weakmap

they are similar to methods in Map.prototype

// demo of methods for WeakMap

const weakm = new WeakMap();

const xkey = { dog: 3 };

// set
weakm.set(xkey, 1);

// get
console.assert(weakm.get(xkey) === 1);

// has
console.assert(weakm.has(xkey));

// delete
weakm.delete(xkey);

console.assert(weakm.has(xkey) === false);

Demo of the auto remove keys

// demo of the auto key removal
const xweak = new WeakMap();

let xobj = { dog: 1 };

xweak.set(xobj, 1);
console.assert(xweak.get(xobj) === 1);

// reset the object
xobj = null;

// the xweak no longer has the key
console.assert(xweak.get(xobj) === undefined);

What is the use of weakmap

// this shows the situation that WeakMap was invented

// create a map
const xmap = new Map();

// create a array of objects, e.g. [ { k: 0 }, { k: 1 }, { k: 2 }, { k: 3 } ]
let xar = Array.from((Array(4)).keys(), (x) => ({ "k": x }));

// add them all to map
xar.forEach((x) => {
 xmap.set(x, 1);
});

console.log(xmap.size);
// 4

// delete our array
xar = null;

// the map now contain objects that wont go away, and there is no reference handle to them except iterating this map
console.log(xmap.size);
// 4