
Practical Use Cases for JavaScript Set and Map

When working in JavaScript, we often find ourselves managing collections of data. Usually, we rely on arrays and plain objects, but sometimes these can feel a bit limited or cumbersome. JavaScript provides two handy data structures that often go overlooked: Set and Map. Each is designed specifically to simplify common tasks like storing unique items or key‑value pairs clearly and efficiently.
In this article, we'll discuss when and why to use Set and Map, look at practical examples that show them in action, and highlight where these built‑in types can simplify your JavaScript code.
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', 'Ellie', 'Sophie']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 allows us to use objects or functions as keys, something that's impossible with plain JavaScript objects:
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}`);});This ensures our items always appear in the order we added them, something plain objects can't reliably guarantee.
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 keys (usually strings).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
JavaScript's built‑in Set and Map objects aren't just extras; they're genuinely helpful tools that simplify common tasks. By knowing when to choose them over plain arrays or objects, we can write code that's clearer, simpler, and easier to maintain.
Key Takeaways
- Use
Setto easily ensure uniqueness and simplify checking existence. - Use
Mapwhen you need flexible keys or need to maintain 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.
Getting comfortable with these built‑in types helps us produce clearer, more maintainable JavaScript code.
Related Articles

Find Peak Element: Binary Search Without a Fully Sorted Array. Gatsby & GraphQL: Nodes vs. Edges. Gatsby & GraphQL: Nodes vs. Edges

HTML Video and the preload Attribute. HTML Video and the
preloadAttribute
Will AI Replace Front‑End Developers? Will AI Replace Front‑End Developers?

Type Coercion in JavaScript: Implicit vs. Explicit Conversion. Type Coercion in JavaScript: Implicit vs. Explicit Conversion

Understanding JavaScript's sort() Method. Understanding JavaScript's
sort()Method
React Hooks: Modern State Management. React Hooks: Modern State Management

Fast and Slow Pointers: Solving the 'Linked List Cycle' Problem. Fast and Slow Pointers: Solving the 'Linked List Cycle' Problem

Optimising Angular Forms: Template‑Driven vs. Reactive Forms. Optimising Angular Forms: Template‑Driven vs. Reactive Forms
ReferenceError: Window is Not Defined in Gatsby. ReferenceError: Window is Not Defined in Gatsby

Understanding the Backtracking Approach: Solving the 'Word Search' Problem. Understanding the Backtracking Approach: Solving the 'Word Search' Problem

Staying Current: Automating Copyright Year Updates. Staying Current: Automating Copyright Year Updates