Intermediate JavaScript Interview QuestionsIntermediateComparison
JavaScript · Question 63
When is Set a better choice than an Array, and how does Set determine uniqueness?
Direct answer
Set is designed for unique membership and uses SameValueZero-style value comparison; arrays are ordered sequences that allow duplicates and provide richer index-based operations.
A Set stores each value at most once and preserves insertion order for iteration. It is often a clearer semantic choice when the operation is “is this value a member?” rather than “what value is at index i?”
- Primitive duplicates collapse as expected;
NaNis treated as the same Set value asNaN, and positive/negative zero are not distinct Set members. - Objects are unique by identity, so two different
{}objects remain two Set entries even if they have the same visible properties. - Arrays are better when duplicates matter, numeric indexing matters, or array transformation APIs and positional semantics dominate.
- Converting
[...new Set(array)]is convenient for primitive/reference-identity deduplication but is not deep deduplication of structurally equal objects.