Set vs Array in JavaScript: Key Differences and Usage
Set is a collection of unique values with no duplicates allowed, while an Array can hold duplicate values and maintains insertion order. Set is ideal for storing unique items and fast membership checks, whereas Array is better for ordered lists and indexed access.Quick Comparison
Here is a quick side-by-side comparison of Set and Array in JavaScript based on key factors.
| Feature | Set | Array |
|---|---|---|
| Duplicates allowed | No, only unique values | Yes, duplicates allowed |
| Order of elements | Insertion order preserved | Insertion order preserved |
| Access by index | No direct index access | Yes, supports index access |
| Performance for membership check | Faster (O(1) average) | Slower (O(n)) |
| Common methods | add(), has(), delete() | push(), pop(), slice(), indexOf() |
| Use case | Unique collections, fast lookup | Ordered lists, indexed data |
Key Differences
Set stores only unique values, so if you try to add a duplicate, it will be ignored. This makes it perfect when you want to ensure no repeated items, like unique user IDs or tags. In contrast, Array allows duplicates and keeps all elements in the order you add them.
Another big difference is how you access elements. Array lets you get items by their position using an index, like arr[0]. Set does not support direct index access; you must iterate over it or convert it to an array first.
For checking if a value exists, Set is faster because it uses a hash-based structure internally, giving average constant time complexity. Arrays require searching through each element, which takes longer as the list grows.
Code Comparison
Here is how you add items and check for duplicates using an Array in JavaScript.
const arr = []; arr.push(1); arr.push(2); arr.push(2); // duplicate allowed console.log(arr.includes(2)); // true console.log(arr);
Set Equivalent
Here is the same example using a Set, which automatically ignores duplicates.
const set = new Set(); set.add(1); set.add(2); set.add(2); // duplicate ignored console.log(set.has(2)); // true console.log([...set]);
When to Use Which
Choose Set when you need to store unique values and want fast checks for existence without duplicates. It is great for filtering unique items or managing collections where duplicates don't make sense.
Choose Array when you need ordered data with duplicates allowed, or when you want to access elements by their position. Arrays are better for lists, queues, stacks, and when you need array-specific methods like sorting or slicing.
Key Takeaways
Set to store unique values and get fast membership checks.Array for ordered collections that allow duplicates and indexed access.Set does not support direct index access; Array does.Set automatically removes duplicates; Array keeps all entries.