12. Set and WeakSet

Set objects are collections of unique values. Duplicate values are ignored, as the collection must have all unique values. The values can be primitive types or object references.

  1. const mySet = new Set([1, 1, 2, 2, 3, 3]);
  2. mySet.size; // 3
  3. mySet.has(1); // true
  4. mySet.add('strings');
  5. mySet.add({ a: 1, b:2 });

You can iterate over a set by insertion order using either the forEach method or the for...of loop.

  1. mySet.forEach((item) => {
  2. console.log(item);
  3. // 1
  4. // 2
  5. // 3
  6. // 'strings'
  7. // Object { a: 1, b: 2 }
  8. });
  9. for (let value of mySet) {
  10. console.log(value);
  11. // 1
  12. // 2
  13. // 3
  14. // 'strings'
  15. // Object { a: 1, b: 2 }
  16. }

Sets also have the delete() and clear() methods.

WeakSet

Similar to WeakMap, the WeakSet object lets you store weakly held objects in a collection. An object in the WeakSet occurs only once; it is unique in the WeakSet’s collection.

  1. const ws = new WeakSet();
  2. const obj = {};
  3. const foo = {};
  4. ws.add(window);
  5. ws.add(obj);
  6. ws.has(window); // true
  7. ws.has(foo); // false, foo has not been added to the set
  8. ws.delete(window); // removes window from the set
  9. ws.has(window); // false, window has been removed