Should You Use JavaScript Maps And Sets?

Spoiler Alert: Maybe.

Mike Cronin
Geek Culture

--

JavaScript Sets and Maps have been around for a few years now, but I still get a lot of questions about them. My students wonder if they should be substituting traditional objects and arrays with these new data types. While there are some killer use cases for sets and maps, you should really look at them like specialized tools and not Swiss army knives.

When to use sets

A Set is a collection, like an array, except each value must be unique. They’re like what would happen if objects and arrays had a baby. Here’s a crash course (set docs):

const mySet = new Set();

mySet.add(1); // add item
mySet.add('a');
mySet.size; // 2
mySet.delete(1)
mySet.has(1); // false
mySet.clear(); // empties set

You need to remove duplicates

This is probably the only time I’ve actually seen sets used in the wild. It’s a handy one liner:

const arr = [1,2,3,4,4,5,6,7,7,7]
const unique = [...new Set(arr)]
// unique equals [1,2,3,4,5,6,7]

You’re doing algorithm challenges

If you’re using anything with set problems, sets are obviously the go to. You can see on the set docs how to implement the basic set actions

--

--

Mike Cronin
Geek Culture

I’m Mostly Focused on JS and web development, but anything coding related is fair game