JavaScript WeakMap and WeakSet

JavaScript WeakMap and WeakSet

·

2 min read


Visual Composer Website Builder


WeakMap

In the previous article, the primitive value was used as the key. This is different in weakMap because the object is the key.

See the example below:

const weakMap = new WeakMap();

const obj = {};
const str = '';

weakMap.set(obj, "correct"); // WeakMap { <items unknown> }
weakMap.set(str, "wrong");  // only use non-primitive data as key
// TypeError: Invalid value used as weak map key

If there's no reference to the object, it gets removed from memory automatically.

See the example below:

let bello = { name: "Bello" };

const weakMap = new WeakMap();
weakMap.set(bello, 'noah');

bello = null; // changed/overriden reference

// bello is removed from memory!

WeakMap does not support iteration methods like keys(), values(), entries().

The following methods still work on WeakMap.

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

The reason behind non-supported iterable methods in WeakMap is that JavaScript engine memory cleanup (full or partial cleanup) may be done immediately or later when more deletions happen.


WeakSet

It is basically used as additional storage of the yes/no or true/false fact of an object like keeping track of people who visited a site:

Mostly only objects are added to WeakSet.

  • Supported methods are add has and delete.
  • It doesn't support size and keys().
  • Like weakMap iteration methods are not supported and also lack the ability to get all current content.

See the example below:

const visitedSet = new WeakSet();

let bello = { name: "Bello" };
const monica = { name: "Monica" };
const jennifer = { name: "Jennifer" };

visitedSet.add(bello); // Bello visited site
visitedSet.add(monica); // Monica visited site
visitedSet.add(bello); // Bello again visited site

// visitedSet has 2 users now

// check if Bello visited the site?
console.log( visitedSet.has(bello) ); // true

// check if Jennifer visited the site
console.log( visitedSet.has(jennifer) ); // false

bello = null; // visitedSet will be cleaned automatically

image.png


Visual Composer Website Builder