Now, we understand the fundamental meaning of weak in the term WeakMap
or WeakSet
. It is not very complex to predict how sets work and how WeakSet
differs from them. Let's take a quick look at the functional difference and then move on to the API.
WeakSet
is very similar to WeakMap
; the values that a WeakSet
can hold are only objects and cannot be primitives just like in the case of a WeakMap
. The WeakSets
are also not enumerable, so you do not have direct access to the values available inside the set.
Let's create a small example and understand the difference between a Set
and a WeakSet
:
var set = new Set(); var wset = new WeakSet(); (function() { var a = {a: 1}; var b = {b: 2}; var c = {c: 3}; var d = {d: 4}; set.add(1).add(2).add(3).add(4); wset.add(a).add(b).add(b).add(d); })(); console.dir(set); console.dir(wset);
One important thing to note is that WeakSet
does not accept primitives and can only accept objects similar to the...