JavaScript Tutorial
JavaScript Sets
A Set stores unique values. add, has, and delete are the usual methods. Duplicates disappear.
A list that forbids duplicates
An array can hold 3 twice. A Set cannot. The second time you add the same value, nothing extra is stored. That is the whole point: membership, not position.
Use a Set when you care whether a value is in the collection, not how many times it appeared or at which index.
Create and add
Pass an iterable to new Set() — often an array. Duplicates in that array vanish on the way in. Then use add for later values.
Example
const tags = new Set(["js", "html", "js", "css"]);
tags.add("dom");
tags.add("html");
console.log(tags.size);
console.log([...tags]);
size is 4: js, html, css,dom. The second js and the second html never became extra items. Spread with [...tags] turns the Set back into an array when you need one.
Click Try it in JavaScript under an example. That opens/javascript/try — a live page and a console.
has and delete
has(value) is a boolean. delete(value) removes that value if it is there and returns whether anything was removed. There is no index: you ask by value.
Example
const seen = new Set();
seen.add("Ada");
seen.add("Lin");
console.log(seen.has("Ada"));
console.log(seen.has("Grace"));
seen.delete("Lin");
console.log(seen.has("Lin"));
console.log(seen.size);
has is the usual test in a loop: skip work you already did, or refuse a name that is already taken.
Loop a Set
for...of walks values in insertion order. forEach does the same. There is no useful numeric index — that is an array habit.
Example
const rooms = new Set(["lab", "studio", "hall"]);
const lines = [];
for (const room of rooms) {
lines.push("open: " + room);
}
console.log(lines.join("\n"));
Set versus array
| Array | Set | |
|---|---|---|
| Duplicates | Allowed | Dropped |
| Order | Index 0, 1, 2… | Insertion order |
| Lookup | includes (scans) | has |
| Count | length | size |
| Add | push | add |
Convert either way: new Set(array) uniques a list.Array.from(set) or [...set] gives you an array again.
What counts as the same
Sets use SameValueZero: 1 and "1" are different.NaN equals NaN here, unlike ===. Objects are compared by identity, not by matching fields — two {} literals are two different values.
Example
const mixed = new Set();
mixed.add(1);
mixed.add("1");
mixed.add(NaN);
mixed.add(NaN);
mixed.add({ id: 1 });
mixed.add({ id: 1 });
console.log(mixed.size);
Size is 5: number 1, string "1", one NaN, and two separate objects. If you need unique objects by id, store the id, not the object.
What to remember
- A Set holds unique values. Extra copies of the same value disappear.
add,has,delete, andsizeare the everyday API.- Walk it with
for...of. Spread it when you need an array. - Objects are unique by identity, not by matching keys.
Next: Maps — keys of any type paired with values, unlike a plain object.