Practical Use Cases for JavaScript Set and Map

Arrays and plain objects are familiar, but they are not always the clearest model for membership or keyed data. Set represents unique values; Map stores keys without turning them into object property strings. Those semantics are more useful than the fact that both APIs are concise.
Practical Uses for JavaScript's Set
A Set is a built‑in object that stores unique values of any type. Unlike arrays, a Set automatically takes care of uniqueness, making certain tasks straightforward.
Quickly Removing Duplicates
One of the most frequent reasons for using a Set is to remove duplicates from an array:
const names = ['Maddie', 'Sophie', 'Maddie', 'Ellie', 'Sophie'];
const uniqueNames = [...new Set(names)]; // ['Maddie', 'Sophie', 'Ellie']This is a much simpler solution compared to writing loops or filtering manually, and it clearly communicates our intention of having unique items.
Efficiently Checking If a Value Exists
If we need to quickly check whether an item already exists in a collection, Set provides efficient lookup:
const activeUsers = new Set(['Sophie', 'Maddie']);
if (activeUsers.has('Sophie')) {
console.log('Sophie is already logged in');
}Checking for existence is faster with a Set compared to looping through arrays, especially with larger datasets.
Tracking Visited Items
When solving problems involving graphs or recursion, we often track visited items to avoid repeating work. A Set is perfect for this:
const visited = new Set<number>();
const dfs = (node: number, graph: Record<number, number[]>) => {
if (visited.has(node)) return;
visited.add(node);
graph[node].forEach(neighbour => dfs(neighbour, graph));
};This clearly shows which nodes we've already seen, avoiding redundant work and infinite loops.
When and Why You Should Use JavaScript's Map
JavaScript's Map lets us store key‑value pairs. It differs from plain JavaScript objects in useful ways, including supporting keys of any type and preserving insertion order.
Using Non‑String Keys
A Map preserves objects and functions as keys by identity. Plain object property keys are strings or symbols, so using an object as a key coerces it to a string and can make distinct objects collide:
const cache = new Map<object, number>();
const user = { id: 123 };
cache.set(user, Date.now());
console.log(cache.get(user)); // retrieves cached timestampThis flexibility makes Map extremely useful for scenarios like caching data associated with specific objects.
Counting Occurrences or Frequencies
Counting occurrences is clearer and easier using a Map compared to an object, especially with dynamic data:
const fruits = ['apple', 'banana', 'apple', 'banana', 'banana'];
const fruitCount = new Map<string, number>();
fruits.forEach((fruit) => {
fruitCount.set(fruit, (fruitCount.get(fruit) || 0) + 1);
});
// fruitCount: {'apple' => 2, 'banana' => 3}This clearly shows the intention of counting items, and we benefit from built‑in methods like .set() and .get().
Keeping Items in Order
A Map keeps track of insertion order, making it ideal when order matters:
const steps = new Map<number, string>();
steps.set(1, 'Login');
steps.set(2, 'Add items to cart');
steps.set(3, 'Checkout');
steps.forEach((value, key) => {
console.log(`${key}: ${value}`);
});Map iteration follows insertion order. Plain object property order is also specified, but integer‑index keys are ordered first, followed by other string keys in creation order and then symbols in creation order; Map is the clearer choice when one insertion order is required.
Quick Comparison: Set, Map, Objects, and Arrays
Here's a brief summary highlighting why you might choose one over another:
Set: Ideal for unique values, fast lookups, removing duplicates.Map: Best for flexible key‑value storage, especially with non‑string keys.Plain Objects:
Good for simple key‑value pairs with known string or symbol keys.Arrays:
Useful for ordered collections of items where duplicates are allowed or desired.
Understanding when to choose each option makes our code clearer and easier to manage.
Wrapping Up
Key Takeaways
- Use
Setto easily ensure uniqueness and simplify checking existence. - Use
Mapwhen key identity matters or when iteration must follow insertion order. - Remember that plain objects and arrays still have their place, but clearly understand when they fall short.
- Writing clear tests ensures our use of these structures remains effective and reliable.
Use Set when membership and uniqueness are the real operations, and Map when keys should retain their original type or are not naturally object property names. Both compare objects by identity. Choose them because that data model fits, not simply because their syntax looks tidier than an array or object.