FrontendDeveloper.in

ECMAScript question detail

Weakmap

WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. For this object, the keys must be objects and the values can be arbitrary values.

Let's see various methods of weakmap with below example,

var weakMap = new WeakMap();

var obj1 = {}
var obj2 = {}

weakMap.set(obj1, 1);
weakMap.set(obj2, 2);
weakMap.set({}, {"four": 4});

console.log(weakMap.get(obj2)); // 2
console.log(weakMap.has({})); // return false even though empty object exists as key. Because the keys have different references

delete obj2;
console.log(weakMap.get(obj2)); // 2
weakMap.delete(obj1)
console.log(weakMap.get(obj1)); //undefined
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399