6

I was reading the WeakMap's description and it said:

In native WeakMaps, references to key objects are held "weakly", which means that they do not prevent garbage collection in case there would be no other reference to the object.

From reading this, my understanding is that WeakMaps are used in instances where you're trying to take advantage of JavaScript's garbage collection. What I don't understand fundamentally is the line I bolded.

Why, in a normal Map, would objects with no references to them not be garbage collected? What's the advantage to this, and do I have to explicitly delete from normal Maps?

m0meni
  • 14,160
  • 14
  • 66
  • 120
  • That means that unless the keys have other, independent references, the gc can reclaim their memories. – Hunan Rostomyan Dec 12 '15 at 01:59
  • @HunanRostomyan I comprehend the concept at face value, but I feel like without an example I can't really understand how the gc really works. – m0meni Dec 12 '15 at 02:01
  • Right, that's a little too abstract. I tried to come up with a little example below. Perhaps that will be a little more useful. – Hunan Rostomyan Dec 12 '15 at 02:16
  • 4
    *"Why, in a normal Map, would objects with no references to them not be garbage collected?"* because the map itself has a reference to the object. As long as there is a reference, the object is not gced. – Felix Kling Dec 12 '15 at 16:25

2 Answers2

1

"Why, in a normal Map, would objects with no references to them not be garbage collected?" because the map itself has a reference to the object. As long as there is a reference, the object is not gced. - Felix Kling

m0meni
  • 14,160
  • 14
  • 66
  • 120
-1

in a normal Map, the Map is a reference to the object

amara
  • 2,057
  • 2
  • 18
  • 26