Tutorial by Examples

WeakMap object allows you to store key/value pairs. The difference from Map is that keys must be objects and are weakly referenced. This means that if there aren't any other strong references to the key, the element in WeakMap can be removed by garbage collector. WeakMap constructor has an optional...
To get a value associated to the key, use the .get() method. If there's no value associated to the key, it returns undefined. const obj1 = {}, obj2 = {}; const weakmap = new WeakMap([[obj1, 7]]); console.log(weakmap.get(obj1)); // 7 console.log(weakmap.get(obj2)); // undefined
To assign a value to the key, use the .set() method. It returns the WeakMap object, so you can chain .set() calls. const obj1 = {}, obj2 = {}; const weakmap = new WeakMap(); weakmap.set(obj1, 1).set(obj2, 2); console.log(weakmap.get(obj1)); // 1 console.log(weakmap.get(obj2)); // 2 ...
To check if an element with a specified key exits in a WeakMap, use the .has() method. It returns true if it exits, and otherwise false. const obj1 = {}, obj2 = {}; const weakmap = new WeakMap([[obj1, 7]]); console.log(weakmap.has(obj1)); // true console.log(weakmap.has(obj2)); // false...
To remove an element with a specified key, use the .delete() method. It returns true if the element existed and has been removed, otherwise false. const obj1 = {}, obj2 = {}; const weakmap = new WeakMap([[obj1, 7]]); console.log(weakmap.delete(obj1)); // true console.log(weakmap.has(obj...
JavaScript uses reference counting technique to detect unused objects. When reference count to an object is zero, that object will be released by the garbage collector. Weakmap uses weak reference that does not contribute to reference count of an object, therefore it is very useful to solve memory l...

Page 1 of 1