Set vs Array in JavaScript: Complete Guide
Compare JavaScript Set and Array across uniqueness, performance, ordering, and access patterns. Learn when to use each collection for your data.
Set and Array are both collections that hold values, but they solve fundamentally different problems. An array is an ordered, indexed list that can contain duplicates. A Set is an unordered collection that guarantees every value is unique.
The right choice depends on whether you care more about position or uniqueness.
The Core Differences
| Set | Array | |
|---|---|---|
| Duplicates | Automatically rejected | Allowed |
| Order | Insertion order (iteration only) | Indexed order |
| Index access | Not supported | Supported (arr[0]) |
| Membership test | has() -- O(1) on average | includes() -- O(n) |
| Size | size property | length property |
| Add element | add() | push(), unshift |
| Remove element | delete() by value | pop, shift, splice by position |
| Duplicate removal | Built-in | Manual or spread with Set |
| Positional methods | None (no push, pop, shift, sort) | Full set of sequence methods |
Uniqueness: The Defining Difference
Adding a duplicate to a Set silently does nothing. Adding a duplicate to an array adds another element:
const set = new Set();
set.add("apple");
set.add("apple");
console.log(set.size); // 1
const arr = [];
arr.push("apple");
arr.push("apple");
console.log(arr.length); // 2This makes Set the natural choice when duplicates must not exist: tracking unique visitors, managing selected items, or storing identifiers.
Membership Testing: Set Is Faster
Set's has() checks membership in roughly constant time, no matter how large the collection gets. Array's includes() has to scan from the beginning until it finds a match or reaches the end:
const largeArray = Array.from({ length: 100000 }, (_, i) => i);
const largeSet = new Set(largeArray);
console.log(largeArray.includes(99999)); // true, but scans up to 100,000 items
console.log(largeSet.has(99999)); // true, near-instant regardless of sizeFor collections with more than a few dozen items, Set is dramatically faster for "does this value exist" checks.
Indexed Access: Array Wins
Array gives you direct access by position. Set does not:
const arr = ["first", "second", "third"];
console.log(arr[1]); // "second"
const set = new Set(["first", "second", "third"]);
console.log(set[1]); // undefinedIf you need the third item, the last item, or to reverse the order, use an array. Set only lets you iterate, not index.
Positional Methods: Array Only
Array has push, pop, shift, unshift, splice, sort, and reverse. Set has none of these because Set is not about position:
const arr = [3, 1, 2];
arr.sort();
console.log(arr); // [1, 2, 3]
const set = new Set([3, 1, 2]);
// set.sort(); // TypeError -- no sort method on SetIf you need to manipulate order, use an array. You can convert a Set to an array, sort it, but the result is a new array, not a sorted Set.
Converting Between Set and Array
The conversion is cheap and common:
// Array to Set (deduplicate)
const numbers = [1, 2, 2, 3, 3, 4];
const unique = new Set(numbers);
// Set to Array (gain index access)
const backToArray = [...unique];
console.log(backToArray); // [1, 2, 3, 4]A practical pattern is using Set for the uniqueness work, then converting to Array when you need array methods like map, filter, or sort. For more on Set basics, see the article on /javascript/javascript-set-object-complete-guide.
When to Use Each
| Scenario | Use |
|---|---|
| Store a list of blog post IDs (must be unique) | Set |
| Store a list of user actions in order (may repeat) | Array |
| Check if a user ID is in a banned list | Set |
| Get the top 10 items by score | Array (needs sorting and slicing) |
| Remove duplicate entries from form submissions | Set |
| Render a list of items in a specific order | Array |
| Track which pages a user has visited | Set |
| Build a queue (FIFO) or stack (LIFO) | Array |
Common Pattern: Using Both Together
Many real-world scenarios use both: Set for uniqueness tracking and Array for sequential operations:
const submittedIds = [101, 102, 101, 103, 102, 104];
// Use Set to find unique IDs
const uniqueIds = [...new Set(submittedIds)];
// Use Array methods for further processing
const sorted = uniqueIds.sort((a, b) => a - b);
const firstThree = sorted.slice(0, 3);
console.log(firstThree); // [101, 102, 103]Each collection does what it is best at. You do not need to pick one and stick with it. For removing duplicates from arrays using Set, the spread operator pattern [...new Set(arr)] is the cleanest approach, also covered in the article on /javascript/removing-duplicates-from-arrays-in-javascript-guide.
Rune AI
Key Insights
- Set guarantees unique values; Array allows duplicates.
- Set.has() is O(1) for membership; Array.includes() is O(n).
- Array has indexed access (arr[2]) and positional methods (push, pop, shift).
- Set has no index access and no duplicate values.
- Convert between them with new Set(arr) and [...set].
Frequently Asked Questions
Is Set faster than Array for checking if a value exists?
Can I access elements in a Set by index?
Does Set preserve insertion order like Array?
Conclusion
Set and Array serve different purposes. Set is for uniqueness and fast membership checks. Array is for ordered lists, indexed access, and sequence manipulation. Convert between them freely and choose based on what your data needs: uniqueness or position.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.