Vanta Logo
SPONSOR
Automate SOC 2 & ISO 27001 compliance with Vanta. Get $1,000 off.
Published
7 min read
Up to date

Trevor I. Lasn

Staff Software Engineer, Engineering Manager

JavaScript Sets and Maps: Beyond Arrays and Objects

How to handle unique values and key-value pairs properly without type coercion and performance issues

Before ES6 introduced Sets and Maps, we had limited options for storing collections of data in JavaScript. We used objects for key-value pairs and arrays for lists. This led to common problems:




What are Sets and Maps?

Sets and Maps are specialized data structures in JavaScript, each designed to solve specific problems that arrays and objects handle poorly.

A Set is a collection of unique values. Think of it like a bag that automatically removes duplicates.

When you add the same value twice, the Set keeps only one copy. It’s perfect for maintaining lists where each item should appear only once.

A Map is a collection of key-value pairs where keys can be any type - numbers, strings, objects, even functions. Unlike objects, which convert all keys to strings, Maps preserve the type of the key. This makes them ideal for creating dictionaries or caches where the key type matters:

Here’s how Sets and Maps solve the two problems we saw earlier with arrays and objects.

Sets and Maps excel at handling data relationships, caching, and uniqueness checks. Each has specific use cases where they outperform traditional arrays and objects.

When to Use Sets

Sets shine when you need fast lookups and uniqueness guarantees in your data. In a tag system, you can instantly check if an article has a specific tag without looping through an array.


When to Use Maps

Maps are perfect when you need to associate data with any type of key - like caching API responses by URL, storing user preferences, or maintaining a relationship between DOM elements and their data.


Performance Trade-offs

Sets and Maps provide O(1) operations through their hash table implementation, compared to arrays which have O(n) for lookups and objects which coerce keys to strings.

However, this speed comes at a cost: Sets and Maps use more memory than arrays and objects. The hash table structure that enables their fast operations requires additional memory overhead to maintain.

For Sets specifically, the hash table ensures that duplicate detection is instantaneous, rather than requiring a full array scan. Maps achieve their performance by using a similar structure but storing both the key and value in the hash table.

Sets and Maps excel at handling user sessions. Sets provide instant O(1) lookups to check if a user is logged in - much faster than searching through an array of user IDs. Maps let us store session data with any type of user identifier (number, string, or object) without key type conversion issues.

The SessionManager example shows how Sets can track unique active users while Maps store detailed session data. This combination is particularly powerful because it separates concerns - the Set handles uniqueness while the Map handles data association.

The instant lookup times make this ideal for high-traffic applications where performance is critical.

When Not to Use Sets and Maps

Sets and Maps come with memory overhead from their hash table structure. For small collections or simple string keys, arrays and objects might be more efficient.

Sets and Maps aren’t just alternatives to arrays and objects - they’re specialized tools that make specific programming patterns more efficient and reliable. Use them when their unique characteristics align with your needs, and you’ll write more robust and performant code.

If you found this article helpful, you might enjoy my free newsletter. I share developer tips and insights to help you grow your skills and career.


More Articles You Might Enjoy

If you enjoyed this article, you might find these related pieces interesting as well. If you like what I have to say, please check out the sponsors who are supporting me. Much appreciated!

Javascript
4 min read

JavaScript Import Attributes (ES2025)

Understanding the new import attributes syntax and why we can't rely on file extensions alone

Nov 10, 2024
Read article
Javascript
7 min read

What's New in Express.js v5.0

A detailed look at the key changes and improvements in Express v5.0 and how to migrate your app

Sep 16, 2024
Read article
Javascript
4 min read

Promise.try: Unified Error Handling for Sync and Async JavaScript Code (ES2025)

Stop mixing try/catch with Promise chains - JavaScript's new Promise.try handles return values, Promises, and errors uniformly

Nov 10, 2024
Read article
Javascript
6 min read

AggregateError in JavaScript

AggregateError helps you handle multiple errors at once in JavaScript. This makes your code easier to manage and more reliable.

Sep 2, 2024
Read article
Javascript
4 min read

What is the JavaScript Pipeline Operator |>

A deep dive into how pipeline operators can make your code more readable and maintainable

Oct 29, 2024
Read article
Javascript
5 min read

Precise Decimal Math in JavaScript with Fraction.js

How to handle exact decimal calculations in JavaScript when floating-point precision isn't good enough

Nov 16, 2024
Read article
Javascript
4 min read

Understanding Bitwise Shifts in JavaScript: << and >>

A practical guide to left and right shift operators in JavaScript

Nov 12, 2024
Read article
Javascript
4 min read

Intl.DurationFormat: Format Time Durations with Locale Support

Stop writing manual duration formatting code. Instead, leverage the new powerful Intl.DateTimeFormat API for internationalized time displays

Mar 13, 2025
Read article
Javascript
3 min read

navigator.clipboard - The New Asynchronous Clipboard API in JavaScript

Copy and paste text, images, and files using the new navigator.clipboard API

Dec 7, 2024
Read article

Become a better engineer

Here are engineering resources I've personally vetted and use. They focus on skills you'll actually need to build and scale real projects - the kind of experience that gets you hired or promoted.

Many companies have a fixed annual stipend per engineer (e.g. $2,000) for use towards learning resources. If your company offers this stipend, you can forward them your invoices directly for reimbursement. By using my affiliate links, you support my work and get a discount at the same!


This article was originally published on https://www.trevorlasn.com/blog/sets-and-maps-in-javascript. It was written by a human and polished using grammar tools for clarity.