1.

What is the difference between Set and WeakSet in ES6?

Answer»

Set: By using the Set() class, users can define an array-like heterogeneous iterable object, which will consist of distinct values. The elements should not just be distinct by values but also by types. i.e. "2" and 2 will be considered as different.

VAR set1= new Set([0, 1, 2]);set1.add(3); // 0, 1, 2, 3set1.add(2); // 0, 1, 2, 3set1.add({x:1, y:2}); // 0, 1, 2, {x:1, y:2}set1.add("GOOD"); // 0, 1, 2, {x:1, y:2}, 'Good' set1.has("Hello"); // falseset1.has("Good"); // trueset1.delete("Good"); // 'Good' deletedset1.has("Good"); // false set1.size; // 4set1.clear(); // Set Cleared

WeakSet(): A WeakSet() is a COLLECTION that is similar to a Set because it retains unique values; but it can only hold Objects. If an object in your WeakSet has no other reference variables left, it will be removed automatically.

 var weakSet1 = new WeakSet([{x:1}]);var ob1 = {o:1};var ob2 = {o:2};weakSet1.has(ob1); //falseweakSet1.add(ob1); weakSet1.add(ob2); weakSet1.has(ob2); // truedelete ob1; // you can't delete objects in this way. Use scope to execute this.myWeakSet.has(ob1); // false, because you deleted ob1, so WeakSet releases it automaticallymyWeakSet.delete(ob2); // ob2 deleted from the setmyWeakSet.add(1); // ERROR, no PRIMITIVE value
SetWeakSet
A set can contain all types of values.A weakSet can only contain objects.
Use .size to find the number of elements.Use .length to find the number of elements.
.forEach() is AVAILABLE for iteration..forEach() is not available for iteration.
Nothing is auto-destroyed.An element object will be auto released to the garbage collector if it has no other reference left.


Discussion

No Comment Found