JavaScript Sets — What Does This Output?
This is a daily Javascript challenge from the CodeShot archive. Practice your knowledge of Set Removes Duplicates Size and improve your technical interview readiness.
const set = new Set([1, 2, 3, 2, 1])
console.log(set.size)
console.log([...set])
Detailed Explanation
# Stop Using Arrays for Everything: A Look at JavaScript Sets
If you've been coding in JavaScript for a while, you've probably spent 99% of your time pushing and popping elements from arrays. Arrays are great, but there are times when they're actually the wrong tool for the job.
That's where Set comes in. It looks like an array, it acts a bit like an array, but the underlying logic is completely different. If you've ever found yourself writing a complex loop just to remove duplicates from a list, you've missed out on one of the cleanest features of the language.
Why This Question Matters
The challenge we're looking at is a classic "gotcha" for developers moving from beginner to intermediate levels:
At first glance, it looks simple. But it tests whether you actually understand how a Set handles data compared to an Array. Many developers assume that because they passed an array with five elements into the constructor, the Set will hold five elements.
In reality, a Set is a collection of unique values. This distinction is the core of the puzzle and a fundamental concept in computer science.
Understanding the Code
Let's break down exactly what's happening here.
First, we have new Set([1, 2, 3, 2, 1]). We are passing an array containing five numbers into the Set constructor. The Set object iterates through that array and adds each element one by one.
However, the rule of the Set is: no duplicates allowed.
When the engine hits the second 2 and the second 1, it doesn't throw an error; it simply ignores them. It sees that those values already exist in the collection and skips them. After the constructor finishes, the Set internally only contains [1, 2, 3].
Next, we see set.size. A common mistake here is trying to use .length. If you've spent years with arrays, your muscle memory will tell you to check .length. But Set doesn't have a length property. It uses .size, which returns the number of unique elements. In this case, it's 3.
Finally, we have [...set]. This is the spread operator. Since a Set is an iterable but not an array, you can't call array methods like .map() or .filter() on it directly. By spreading the set into a new array literal, we convert the Set back into a standard JavaScript array.
Finding the Correct Answer
If this were a multiple-choice question, the correct answer (Option B) would be:
3
[1, 2, 3]
Why not the others?
- Option A (5, [1, 2, 3, 2, 1]): This assumes the Set behaves like an array. It doesn't.
- Option C (3, {1, 2, 3}): This is a trick. While the Set *is* a set, console.log([...set]) explicitly converts it into an array. The output will be in array brackets [], not curly braces {}.
- Option D (undefined, [1, 2, 3]): This assumes .size doesn't exist or that the constructor failed.
Common Mistakes Developers Make
The most frequent slip-up is the .length vs .size confusion. I've seen senior devs spend five minutes debugging a "null" value only to realize they were calling .length on a Set.
Another tricky area is how Set handles objects. If you try to put two identical-looking objects into a set, it won't work the way you think:
Why? Because in JavaScript, objects are compared by reference, not by value. Even though those two objects *look* the same, they point to different locations in memory. To a Set, they are completely different entities.
Real-World Usage
In a production environment, you won't usually use a Set just to pass a technical interview. You'll use it for performance and data integrity.
The most common use case is deduplication. If you're fetching a list of tags from an API and you want to display a unique list of categories in a UI dropdown, the fastest way to do that is:
This is significantly faster and cleaner than using .filter() with .indexOf(), which has a time complexity of $O(n^2)$. A Set handles this in $O(n)$, making it the go-to choice for large datasets.
You'll also see Set used for tracking "seen" items in algorithms (like finding a cycle in a linked list or traversing a graph) because checking if an item exists in a Set using .has() is nearly instantaneous, regardless of how many items are in the collection.
Key Takeaways
- Unique Values Only: A Set automatically strips out duplicates.
- .size not .length: Remember that Set uses .size to count elements.
- The Spread Trick: Use [...set] to quickly convert a Set back into an array when you need to use array methods.
- Reference Matters: Be careful with objects and arrays inside sets; they are compared by reference, not by their content.
- Performance: Use Set for deduplication and membership checks to keep your code efficient.
Why this matters
Understanding Set Removes Duplicates Size is crucial for passing technical interviews. In real-world applications, this concept often leads to subtle bugs if not handled correctly. For more details, you can always refer to the official MDN Documentation.