0

I noticed something, when i create an object and set it in WeakMap(), it is stored within WeakMap(), but when i re-assign this variable with value "null", "Grabage collector" remove this key from WeakMap(), because no reference to it.

let object1 = { name: "A" };
const map1 = new WeakMap();
map1.set(object1, "Apple");
console.log(map1.has(object1)); // true
object1 = null; // now garbage collector will remove the object from WeakMap

The Question Here: when i pass an object literal directly as a param in WeakMap(), why this object wouldn't been removed? because it hasn't any reference for it

map1.set({ name: "D" }, "Direct");
//Why map accept this param, although no reference for it

UPDATE: it would been removed as well in case you pass literal object directly to WeakMap

Anonumouz
  • 62
  • 6
  • 2
    Why do you say the object wouldn't be removed? There are no other references to it, it should be eligible for garbage collection. – VLAZ Jul 22 '22 at 12:55
  • 2
    What makes you think it won't be removed? – evolutionxbox Jul 22 '22 at 12:56
  • Thank You so much, I thought it won't been removed, because it accept it as parameter but it will been removed as well! now make sense – Anonumouz Jul 22 '22 at 13:00

0 Answers0