JavaScript Notes
Master the JavaScript Set data structure for storing unique values. Learn add, has, delete, iteration, Set operations (union, intersection, difference), WeakSet, and Set interview questions.
A Set is a built-in JavaScript collection that stores unique values of any type. Attempting to add a duplicate value is simply ignored — Set automatically ensures every element appears exactly once. It remembers insertion order and supports fast O(1) lookups.
💡 Key insight: A Set is like a mathematical set: each element is unique. It's the most efficient JavaScript tool for deduplication and membership testing.
Creating a Set
Set(4) { 1, 2, 3, 4 }
4
Set(3) { 'b', 'a', 'n' }Core Methods
const fruits = new Set();
// add — adds value (returns the Set, chainable)
fruits.add("apple");
fruits.add("banana");
fruits.add("cherry");
fruits.add("apple"); // duplicate — ignored
console.log(fruits.size); // 3
// has — O(1) membership test
console.log(fruits.has("banana")); // true
console.log(fruits.has("mango")); // false
// delete — remove a value
fruits.delete("banana");
console.log(fruits.size); // 2
// clear — remove all values
fruits.clear();
console.log(fruits.size); // 03 true false 2 0
Iterating a Set
"red" "green" "blue" "Color: red" "Color: green" "Color: blue" ["red", "green", "blue"] ["red", "green", "blue"]
Remove Duplicates from an Array
[1, 2, 3, 4, 5] ["js", "css", "html"]
Set Math Operations
JavaScript Set doesn't have built-in union/intersection, but they're easy to implement:
"Union: [1, 2, 3, 4, 5, 6, 7]" "Intersection: [3, 4, 5]" "Difference A-B: [1, 2]" "Symmetric Diff: [1, 2, 6, 7]" "A ⊆ B: false"
Using Set for Fast Lookup
true false
Array.includes()is O(n) — it scans every element.Set.has()is O(1) — hash-based. For 100,000 items,Set.has()is dramatically faster.
Set vs Array Performance
| Operation | Set | Array |
|---|---|---|
Membership check (has / includes) | O(1) | O(n) |
| Add unique element | O(1) | O(n) (need to check first) |
| Delete | O(1) | O(n) (filter/splice) |
| Iteration | O(n) | O(n) |
| Index access | ❌ Not supported | ✅ O(1) |
| Duplicates | ❌ Prevented | ✅ Allowed |
When to Use a Set
✅ Use Set when:
- You need a unique collection of values
- You need fast membership testing (O(1)
has) - You want to deduplicate an array in one line
- You're doing set math (union, intersection, difference)
- Tracking visited nodes in graph algorithms
❌ Use Array when:
- You need duplicates
- You need index access (
arr[0]) - You need
map,filter,reduce(convert to array first) - Order by index matters
Common Mistakes
- Checking for value equality with objects —
new Set([{a:1}, {a:1}]).sizeis2, not1. Objects are compared by reference, not value. - Modifying a Set while iterating — safe in JS (unlike some languages), but it's still bad practice.
- Expecting
set[0]to work — Set has no index access. Spread to array first. - Not converting back to an array for
map/filter— Set doesn't have these methods.
Interview Questions
Q1. What is a JavaScript Set and what makes it different from an array?
A Set is an ordered collection of unique values with O(1) membership testing. Unlike arrays, Sets reject duplicates and don't support index access. They're ideal for deduplication and fast lookups.
Q2. What is the time complexity of Set.has()?
O(1) average — Set uses a hash table internally, so lookups are constant time regardless of the size of the Set.
Q3. How do you remove duplicate values from an array using Set?
[...new Set(array)]orArray.from(new Set(array)). This creates a Set (which drops duplicates) and spreads it back into a new array.
Q4. Does Set maintain insertion order?
Yes. Iterating a Set always yields values in the order they were first inserted.
Q5. Can a Set store objects? What happens with {a:1} and {a:1}?
Yes, a Set can store objects. But{a:1}and{a:1}are two *different object references*, so both are stored as separate entries. Sets use reference equality for objects, not structural equality.
Q6. How do you implement Union and Intersection of two Sets?
``js const union = new Set([...setA, ...setB]); const intersection = new Set([...setA].filter(x => setB.has(x))); ``Q7. What is the difference between Set and WeakSet?
Setcan hold any value type and is fully iterable.WeakSetcan only hold objects (no primitives), doesn't prevent garbage collection of its items (weak references), is not iterable, and has nosizeproperty.WeakSetis used for tracking objects without causing memory leaks.
Q8. When would you use a Set instead of an array for performance?
When you need to frequently check membership.array.includes(x)is O(n) — it scans every element.set.has(x)is O(1). For a blacklist, visited-node tracker, or deduplication of large datasets, Set is significantly faster.
Key Takeaways
- Set stores unique values only — duplicates are silently ignored.
has()is O(1) — much faster thanArray.includes()for large collections.- Spread
[...new Set(arr)]is the cleanest one-liner for array deduplication. - Set supports set math via spread + filter: union, intersection, difference, symmetric difference.
- Objects in Sets are compared by reference — two structurally identical objects are different Set entries.
WeakSetis the garbage-collection-friendly variant for tracking object references.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Set — Unique Values Data Structure Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, data, structures, set
Related JavaScript Master Course Topics