JavaScript Map and Set

John Wolfe
2 min readJul 23, 2021

Today, I ran into the use of map and set in JavaScript. Although these are fairly basic JavaScript concepts, it had been awhile since I’d seen them in practice, so this is a quick refresher on these concepts.

Set

A set is a feature of JavaScript that like an object can store all different types of primitive and non-primitive values. One frequent use of a set in JavaScript is to remove duplicate values from an array. For example, the below:

const array1 = [ 1, 1, 2, 3, 4 ]const myset = new Set(array1)console.log(array1)=> { 1, 2, 3, 4 }

Similar to an array, a Set has a variety of methods you can use to operate on it. However, I’ll let you investigate those if you’re interested.

Map

While a set is an array-like object, a JavaScript map is more closely related to typical Javascript object with some unique features. Although I’ve never verified, maps are generally understood to be slightly more performant than objects.

One difference between a map and an object is that while the keys in an object have to be strings and single entities, in a map they can be anything — even objects. Consider the example below:

const a = { "food": "pizza" };
const b = {};
const myMap = new Map([[a, 'a'], [b, 'b']])
console.log(myMap)
=> { { food: 'pizza' } => 'a', {} => 'b' }

--

--

John Wolfe

Software developer Tata Consultancy Services. React, Rails, and Java. Former content editor for @Quora and @inversedotcom. I live in Chicago, Illinois.