/    /  Javascript-WeakMap

Javascript-WeakMap

 

The JavaScript  WeakMap object is a type of collection of keys or values pairs in which the keys are weakly referenced. The keys are objects and also the values can be arbitrary values.

 

Syntax:

 

new WeakMap([iterable])

 

Instance methods:

 

  • WeakMap.prototype.delete(key) – WeakMap.prototype.has(key) will return false afterwards.
  • WeakMap.prototype.get(key) – The value connected with the key, or undefined if there is none.
  • WeakMap.prototype.has(key) – Boolean asserting whether a value has been connected with the key in the javascript WeakMap object or not.
  • WeakMap.prototype.set(key, value) – Sets the values for the keys in the javascript WeakMap object. Returns the WeakMap object.

 

  • This object allows the keys of object type only.
  • They are targeted to garbage collection.
  • It doesn’t provide any method to get the list of keys( not enumerable).
  • Its elements in insertion order.

 

Using WeakMap:

 

const wm1 = new WeakMap(),
   wm2 = new WeakMap(),
   wm3 = new WeakMap();
const o1 = {},
   o2 = function() {},
   o3 = window;

wm1.set(o1, 37);
wm1.set(o2, 'azerty');
wm2.set(o1, o2); // a value can be anything, including an object or a function
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!

wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, because there is no key for o2 on wm2
wm2.get(o3); // undefined, because that is the set value

wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (even if the value itself is 'undefined')

wm3.set(o1, 37);
wm3.get(o1); // 37

wm1.has(o1); // true
wm1.delete(o1);
wm1.has(o1); // false