WeakMap

  • References to keys/values held weakly

  • Do not prevent garbage collection

  • Small api ( add, delete, check for values ) compared to set/map

  • cann't be iterated

  • Have no size as it does garbage collected

Note

  • keys must be objects

  • the values can be arbitrary values.

var wm = new WeakMap();
wm.add()
wm.delete()
wm.has()

WeakMap Use Case

let dog1 = {name: 'Tomy'};
let dog2 = {name: 'Tuffy'};

const strongMap = new Map();
const weakMap = new WeakMap();

strongMap.set(dog1, 'Tomy is the best');
weakMap.set(dog2, 'Tuffy is the best');

dog1 = null;
dog2 = null;

// strongMap.size => 1
// WeakMap.size => undefined
strongMap -> Map(1) {Object {name: "Tomy"} => "Tomy is the best"}
weakMap -> WeakMap {} // expected, as it garbage collected item in it, because dog1 reference is null now

WeakMap Demo

var wm = new WeakMap();
wm.set({name: 'hemant'}, 30).set({age: 20}, function(){ return 'your age'; })
console.log(wm); // WeakMap {Object {name: "hemant"} => 30, Object {age: 20} => function}

Last updated

Was this helpful?