Set & WeakSet
EasyIn plain terms
Set stores unique values (no duplicates). Methods: add, has, delete, size. WeakSet holds objects only; does not prevent garbage collection. Iterable with for...of.
What you need to know
- •Unique values only
- •add, has, delete
- •WeakSet: objects only, weak refs
Try it yourself
Copy the code below and run it in your browser console or a code editor:
const set = new Set([1, 2, 2, 3]);
set; // Set(3) {1, 2, 3}
set.add(4);
set.has(2); // true
set.delete(2);
set.size; // 3
for (const v of set) {
console.log(v);
}
const ws = new WeakSet();
ws.add({}); // only objects
// No size, no iterationLearn more
Dive deeper with these trusted resources: