The Sets lesson introduced the essentials. This lesson is the complete toolkit: every method and property a Set has, how to loop in different ways, and how to move data between Sets and arrays.
| Member | Does | Returns |
|---|---|---|
| add(value) | Add a value (if not already there) | the Set |
| has(value) | Check membership | true / false |
| delete(value) | Remove a value | true if it was there |
| clear() | Remove everything | undefined |
| size | Property: how many values | number |
| forEach(fn) | Run fn on each value | undefined |
| values() / keys() / entries() | Iterators for looping | iterator |
Because add returns the Set itself, you can call it several times in a row:
const s = new Set().add("a").add("b").add("a").add("c");
console.log(s.size); // 3
const online = new Set(["ava", "ben"]);
console.log(online.delete("ben")); // true (was there, now removed)
console.log(online.delete("zed")); // false (was never there)
const cart = new Set(["pen", "tape"]);
cart.clear();
console.log(cart.size, cart.has("pen"));
A common pattern for things like "favorite" buttons or selected items:
const favorites = new Set();
function toggle(item) {
if (favorites.has(item)) {
favorites.delete(item);
} else {
favorites.add(item);
}
}
toggle("song-12");
toggle("song-40");
toggle("song-12"); // un-favorited
console.log([...favorites]);
const planets = new Set(["Mercury", "Venus", "Earth"]);
// 1. for...of (most common)
for (const p of planets) console.log(p);
// 2. forEach
planets.forEach(p => console.log(p));
// 3. an explicit iterator
for (const p of planets.values()) console.log(p);
All three visit values in the order they were first added.
The forEach callback can also be a regular function. It receives the value twice and then the Set, for the same reason explained in the next section:
const letters = new Set(["a", "b"]);
letters.forEach(function (value, sameValue, set) {
console.log(value, sameValue, set.size);
});
values(), keys(), and entries() return an iterator, not an array. If you save one in a variable, you can only loop through it once. After that it is empty: const it = letters.values(); [...it] gives ["a", "b"], but a second [...it] gives []. Call values() again for a fresh one, or just loop the Set itself.
Sets have no keys, only values. These methods exist so Sets and Maps can be used with the same code. On a Set, keys() is the same as values(), and entries() gives each value twice:
const s = new Set(["x", "y"]);
console.log([...s.entries()]);
// Array to Set
const set = new Set([3, 1, 3, 2]);
// Set to array (either way works)
const arr1 = [...set];
const arr2 = Array.from(set);
Sets do not have map, filter, or sort. Convert to an array, use the array method, and convert back if needed:
const scores = new Set([72, 95, 88, 61]);
const high = new Set([...scores].filter(s => s >= 80));
const sorted = [...scores].sort((a, b) => a - b);
console.log(high, sorted);
There is no way to edit a value in place. Delete the old one and add the new one:
const names = new Set(["ava", "ben"]);
names.delete("ben");
names.add("Ben");
What does this log?
const it = new Set(["x", "y"]).values();
console.log([...it].length, [...it].length);
2 0. An iterator can only be used once. The first spread uses it up, so the second finds nothing.Why can you write new Set().add("a").add("b")?
add returns trueadd returns the Set itselfadd returns the new sizeadd returns the same Set, so the next .add is called on it. (delete is different: it returns true or false.)What does this log?
const s = new Set([1, 2]);
s.clear();
console.log(s.size, s.has(1));
0 false. clear removes every value but keeps the (now empty) Set.add calls, predict the size, then run ittoggle function and toggle several items on and off[...set.entries()] for a Set of three numbers