0

I go through the documentation of Map and WeakMap of javascript from MDN web docs.

but in this (Why WeakMap?) topic I did not get second point that is how WeakMap prevent memory leak while Map does not.

will somebody explain it briefly with some sort of example.

--edits--

Actually I wanted to know how WeakMap holds weak references or how it is implemented.

but now i got this answer and explained here

Ravi Sevta
  • 1,966
  • 14
  • 29

2 Answers2

2

Consider an implementation for a LinkedList or a Tree. You might not want to expose next, last, children, or parent as a property, but instead make it a property accessor that checks a static WeakMap for the existence of such relationships. This way, your implementation allows the relationships to maintain weak connections.

HTML elements are a good way of explaining this. Let's say you partially implement an HTML element:

const HTMLElement = (() => {
  const children = new WeakMap()

  class Node {
    constructor () {
      children.set(this, [])
    }

    get children () {
      return children.get(this)
    }

    appendChild (element) {
      children.get(this).push(element)
      return element
    }

    removeChild (element) {
      const elements = children.get(this)
      elements.splice(elements.indexOf(element), 1)
      return element
    }
  }

  return class HTMLElement extends Node {
    constructor (tag) {
      super()
      this.tagName = tag.toUpperCase()
    }

    toString () {
      return `<${this.tagName}>${children.get(this).join('')}</${this.tagName}>`
    }
  }
})()

{
  const p = new HTMLElement('p')

  p.appendChild(new HTMLElement('a'))
  p.appendChild(new HTMLElement('span'))

  console.log(`${p}`)
}
// a and span get GC'd when reference to p is lost
console.log(typeof p)

If children was a Map, you'd have a memory leak when the reference to p is lost, because the others would still have strong references since HTMLElement is still accessible.

Patrick Roberts
  • 40,065
  • 5
  • 74
  • 116
1

It's explained in the article you linked

By contrast, native WeakMaps hold "weak" references to key objects, which means that they do not prevent garbage collection in case there would be no other reference to the key object.

WeakMaps do not directly reference the keys, and therefore when all other references of the keys run out, the keys can still be garbage-collected, therefore no memory leak

TKoL
  • 10,782
  • 1
  • 26
  • 50