JS Sets
JS Sets
A Set is a collection of unique values. If you add the same value multiple times, it will only exist once.
const set = new Set();
set.add("a");
set.add("b");
set.add("b"); // duplicate ignored
console.log(set.size); // 2
console.log(set.has("a")); // true
Sets are useful for removing duplicates from arrays.
const nums = [1, 2, 2, 3, 3, 3]; const unique = [...new Set(nums)]; console.log(unique); // [1,2,3]
JS Set Methods
Common Set methods include add, has, delete, clear, and forEach.
const letters = new Set(["a", "b", "c"]);
letters.add("d");
console.log(letters.has("c")); // true
letters.delete("b");
console.log(letters.size); // 3
letters.forEach((value) => {
console.log(value);
});
You can iterate over a Set using for...of.
const colors = new Set(["red", "green", "blue"]);
for (const c of colors) {
console.log(c);
}
JS Set Logic
Sets make it easy to implement common set operations like union, intersection, and difference.
const a = new Set([1, 2, 3]); const b = new Set([3, 4, 5]); // Union const union = new Set([...a, ...b]); // Intersection const intersection = new Set([...a].filter(x => b.has(x))); // Difference (A - B) const difference = new Set([...a].filter(x => !b.has(x))); console.log([...union]); // [1,2,3,4,5] console.log([...intersection]); // [3] console.log([...difference]); // [1,2]
JS Set WeakSet
WeakSet is similar to Set but it only stores objects and does not prevent them from being garbage-collected.
WeakSet is not iterable and has no size. It is mainly used for tracking objects privately.
const visited = new WeakSet();
let user = { id: 1 };
visited.add(user);
console.log(visited.has(user)); // true
user = null; // object can be garbage-collected
JS Set Reference
Sets are ideal for uniqueness, fast lookups, and set operations. Key methods include add(), has(), delete(), clear(), and iteration via for...of.
Next Step
Continue with JS Maps to store key-value pairs with any key type.