Practical Use Cases for JavaScript Set and Map

Hero image for Practical Use Cases for JavaScript Set and Map. Image by Nik Shuliahin.
Hero image for 'Practical Use Cases for JavaScript Set and Map.' Image by Nik Shuliahin.

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 keyvalue 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 builtin types can simplify your JavaScript code.


Practical Uses for JavaScript's Set

A Set is a builtin 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 keyvalue 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 timestamp

This 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 builtin 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 keyvalue storage, especially with nonstring keys.
  • Plain Objects:

    Good for simple keyvalue 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 builtin 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 Set to easily ensure uniqueness and simplify checking existence.
  • Use Map when 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 builtin types helps us produce clearer, more maintainable JavaScript code.


Categories:

  1. Development
  2. ES6
  3. Front‑End Development
  4. Guides
  5. JavaScript