Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between ES6 Set and WeakSet?

ECMAScript 6 has these very similar collections: Set and WeakSet. What is the difference between them?

like image 648
Luboš Turek Avatar asked Apr 10 '17 09:04

Luboš Turek


People also ask

What is the difference between set and WeakSet?

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.

What is the difference between set map and WeakSet WeakMap?

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.

What is WeakSet in JavaScript?

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)


2 Answers

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:

  • Sets can store any value. WeakSets are collections of objects only.
  • WeakSet does not have size property.
  • WeakSet does not have clear, keys, values, entries, forEach methods.
  • WeakSet is not iterable.
like image 199
Luboš Turek Avatar answered Sep 25 '22 21:09

Luboš Turek


Summary:

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:

  1. Weaksets can only hold objects within its collection, no primitive values (e.g. int, boolean, string) are allowed.
  2. References to the objects are held weak. This means that whenever there is no other reference towards the object besides the WeakSet, the object can be be garbage collected (i.e. the JS engine will free the memory which object the reference was pointing to).

Example:

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)); 
                     
like image 21
Willem van der Veen Avatar answered Sep 24 '22 21:09

Willem van der Veen