ECMAScript 6 has these very similar collections: Set
and WeakSet
. What is the difference between them?
Just as with Set s, each object in a WeakSet may occur only once; all objects in a WeakSet 's collection are unique. The main differences to the Set object are: WeakSet s are collections of objects only. They cannot contain arbitrary values of any type, as Set s can.
WeakMap is Map -like collection that allows only objects as keys and removes them together with associated value once they become inaccessible by other means. WeakSet is Set -like collection that stores only objects and removes them once they become inaccessible by other means.
WeakSet in JavaScript is used to store a collection of objects. It adapts the same properties of that of a set i.e. does not store duplicates. The major difference of a WeakSet with the set is that a WeakSet is a collection of objects and not values of some particular type. Syntax: new WeakSet(object)
The main difference is that references to objects in Set are strong while references to objects in WeakSet are weak. This means that an object in WeakSet can be garbage collected if there is no other reference to it.
Other differences (or rather side-effects) are:
Weaksets are javascript objects which holds a collection of objects. Due to the nature of a set only one object reference of the same object may occur within the set. A Weakset differs from a normal set in the following ways:
int
, boolean
, string
) are allowed.WeakSet
, the object can be be garbage collected (i.e. the JS engine will free the memory which object the reference was pointing to). let myWeakSet = new WeakSet();
let obj = {};
myWeakSet.add(obj);
console.log(myWeakSet.has(obj));
// break the last reference to the object we created earlier
obj = 5;
// false because no other references to the object which the weakset points to
// because weakset was the only object holding a reference it released it and got garbage collected
console.log(myWeakSet.has(obj));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With