Difference between Set and WeakSet - kdaisho/Blog GitHub Wiki

You know, an if you create an object and set it to a variable. The variable is just a reference to where the object is stored in memory.

And if you create a set instance using Set and add the object.

Set

const s = new Set()

let obj = {
  me: true
}

s.add(obj)
s.has(obj) // true

// deleting the reference of `obj`
obj = null

// you've lost the reference so this returns false
s.has(obj) // false

// but you can still get the value, because `obj` hasn't been garbage collected as `s` still holds a reference.
for (const v of s) {
  console.log(v) // {me: true}
}

WeakSet

const ws = new WeakSet()

let obj2 = {
  me: true
}

ws.add(obj2)
ws.has(obj2) // true

// deleting the reference
obj2 = null

// you've lost the reference so it returns false
ws.has(obj2) // false

// obj2 will be garbage collected sooner or later because `ws` won't hold the reference.