Set
Unique values with add, has, delete and size.
Set stores unique values. WeakSet stores object references weakly for specialized membership tracking.
const tags = new Set(["html", "css", "html"]);
console.log(tags.size);
console.log(tags.has("css"));
Arrays & Collections
A Set stores each value only once. Adding the same value again does not create a duplicate.
Set is iterable, so it works with for...of and spread. Converting a Set back to an array is common when you want unique list values.
WeakSet only accepts objects and does not expose size or iteration. It is useful for private membership tracking without preventing garbage collection.
Unique values with add, has, delete and size.
Use [...new Set(array)] for simple deduping.
Weak object membership without iteration.
has checks whether a value is present.
Examples
const selectedIds = new Set();
selectedIds.add("a1");
selectedIds.add("a1");
console.log(selectedIds.size); // 1
const selectedIds = [];
if (!selectedIds.includes("a1")) {
selectedIds.push("a1");
}
Code patterns
These are the patterns developers search for constantly: reading items, copying arrays, choosing map/filter/reduce, sorting with a comparator, destructuring and using Set or Map.
Duplicate values are ignored.
const tags = new Set(["html", "css", "html"]); console.log(tags.size);
Use add and has for membership.
const selected = new Set();
selected.add("html");
console.log(selected.has("html"));
Convert through Set to remove duplicates.
const tags = ["html", "css", "html"]; const uniqueTags = [...new Set(tags)];
Track objects without exposing iteration.
const seen = new WeakSet();
const record = {};
seen.add(record);
console.log(seen.has(record));
Rules that matter
Arrays and collections are not just storage. They describe whether the code is selecting, transforming, grouping, counting, sorting or enforcing uniqueness.
It communicates that duplicates are not allowed.
It reads cleanly and is efficient.
Use [...set] when you need map or filter.
Two separate object literals are different values.
Primitive values are not allowed.
WeakSet is intentionally not enumerable.
Production thinking
Set removes a lot of duplicate-checking boilerplate and makes uniqueness a data-structure rule.
Selected item collections can use Set to prevent duplicate states in rendered controls.
Production code should use Set when uniqueness is part of the model, not an afterthought.
Sets can help remove duplicate generated links or tags before rendering.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
A collection method should tell the reader what kind of operation is happening before they read the callback body.