Site icon i2tutorials

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:

 

 

 

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
Exit mobile version