Reputation: 6615
ECMAScript 6 has these very similar collections: Set
and WeakSet
. What is the difference between them?
Upvotes: 33
Views: 16114
Reputation: 1
Example will be more clear if written like this:
let myWeakSet = new WeakSet();
let x = {name:"ali",age:38};
myWeakSet.add(x);
x = 5;
console.log(myWeakSet);
Then:
let mySet = new Set();
let x = {name:"ali",age:38};
mySet.add(x);
x = 5;
console.log(mySet);
In the first example console will show you that WeakSet
contain no objects because another value was assigned to object reference (x) but in second example console will show you that the Set contained an object and by making mySet
iterable you can see the properties of object (x) you have added to mySet
:
console.log(mySet.values().next().value);
Upvotes: -1
Reputation: 36640
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));
Upvotes: 12
Reputation: 51
Set:- A Set is a collection of values, where each value may occur only once. And main method are add, delete, has, clear and size.
WeakSet:- WeakSet objects allows you to store collection of unique key.“WeakSet” keys cannot be primitive types. Nor they can be created by an array or another set. Values of WeakSet must be object reference.
Upvotes: 4
Reputation: 105
Upvotes: 1
Reputation: 6615
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:
Upvotes: 35