Monday, April 16, 2018

WeakMap and WeakSet

WeakMap and WeakSet is little different because it does not prevent from memory. You may understand it after seeing the example.

We can not use keys as primitives in weakmap.


let weakMap = new WeakMap();

let obj = {};

weakMap.set(obj, "ok"); // works fine (object key)

weakMap.set("test", "Whoops"); // Error, because "test" is a primitive

If you are trying to use primitives in weakmap, simply it will through an error. (above example).

Example II:


let john = { name: "John" };

let weakMap = new WeakMap();
weakMap.set(john, "...");

john = null; // overwrite the reference

// john is removed from memory!

alert(john); //null

Below is the main part of weakmap. Furthermore , you can not access john after set it to null.

Weak map have some limitation in methods, because of some technical reason. Because, we should allow javascript engine to do the clean work. Means, clean should do immediately or later or parallel.

1. weakMap.get(key)

2. weakMap.set(key, value)

3. weakMap.delete(key, value)

4. weakMap.has(key)

WeakSet also same like weak map.

No comments:

Post a Comment