Sets

var s = new Set().add(3).add(3);
console.log(`size of set is ${s.size}`); // size of set is 1

var obj = {a: 1, b: 2};
s.add(obj).add({a: 1, b: 2});
console.log(`size of set is ${s.size}`); // size of set is 3

Set

The Set object holds a collection of unique values. Uniqueness is provided by the === operator. You can iterate over the elements of a set in insertion order.

Property size retrieves a number of elements in set.

methoddescription
add(v) Adds value. Returns a set object.
delete(v) Removes value from set. Returns false if the value did not exist.
has(v) Returns true if given value exist in set.
forEach(cb [, thisArg]) Executes callback function for every value. Callback functions has 3 parameters :
  • val - value
  • key - key, same value as val
  • map - set itself
thisArg parameter provides a this value for callback function.
entries() Returns iterator for iterating over all entries of set. Although Set don't need keys it keeps the API similar to the Map object. Each entry has the same value for its key and value.
values() Returns iterator for iterating over all values of set in insertion order.
clear() Removes all values from set.

WeakSet

The WeakSet object holds a collection of unique weakly referenced values. So values must be objects. When value not used anywhere, it will be removed from set by garbage collector. So you can't iterating over elements.

WeakSet has only 3 methods: add(v), delete(v), has(v).