Sets: uniqueness and set operations
The set operation methods (union and friends) are ES2025; the last line is the older way to intersect. Two look-alike objects are still two values.
Map is a key-value collection whose keys can be any value (objects included) and which remembers insertion order; Set is a collection of unique values. Both are iterable, have a real size, and are built for frequent adding, looking up and removing.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write firstRepeat(list) that returns the first value that appears a second time, using a Set. firstRepeat(["a", "b", "c", "b", "a"]) should return "b".
Given const orders = [["tea", 2], ["pen", 1], ["tea", 3]], build a Map of total quantity per item and log it.
Two classes share some students: const x = new Set(["Asha", "Ravi", "Meera"]) and const y = new Set(["Ravi", "Kabir"]). Log the students in both, and everyone in either.
Explain it without notes
When would you choose a Map over a plain object?
How do Map and Set compare keys and values? What happens with NaN and with objects?
How do you remove duplicates from an array, and what are the limits of that method?
Name the ES2025 set methods and say what each returns.
Preview
Console
Nothing logged yet.Expected console output
Set(3) { 'js', 'css', 'html' }
3 true
[ 3, 1, 2 ]
Set(2) { NaN, 0 }
2
Set(5) { 1, 2, 3, 4, 5 }
Set(2) { 3, 4 }
Set(2) { 1, 2 }
Set(3) { 1, 2, 5 }
true true
Set(2) { 3, 4 }