Map vs. Set vs. Object in Javascript

Osgood Gunawan
3 min readDec 14, 2020

Developers often spend much time deciding the correct data structure to use. Choosing the right data structure can make it easier to operate data, saving time, and making code more comprehensive. The two most prevailing data structures for storing collections of data are Objects and Arrays. Developers use Objects to store key/value pairs and Arrays to store indexed lists. However, ECMAScript 2015 introduced two new types of iterable objects: Sets and Maps; these are ‘keyed collections,’ which means their behavior is slightly different and offers performance advantages.

The difference between Map and Object

There are two main differences between Map and a traditional Object in Javascript.

Direct iteration

Iterating over keys, values, or entries in a regular object, we must convert them to an array, utilize a method such as an Object.keys(), Object.values(), Object.entries or for…in loop.The object is not directly iterable; for…in loop only able to iterates over enumerable properties of objects, non-symbol properties and it does so in an arbitrary order.

With a Map, we are directly iterable, and the order of iteration is the same as the order of insertion. We can use for…of or forEach to iterate over Map’s entries.

Unrestricted Keys

Javascript Object key must be either a String or a Symbol.

As for Map, we allow the use of other primitive types(includes NaN). This gives developers advantages when it comes to associating with other different data types.

The difference between Map and Set

A Set is a collection dataset that needs to be composed of unique values, where a Map is when you have pairs of associated data when we map the keys to the value. Map and Set both have similar methods; these include .has(), .get(), .delete(), and .size().

The difference is that a Map comes with a key/value pair, two dimensions. We can convert an array to set as well as a 2D array to map:

Overall depends on the problem scenario of using what kind of data structure the developer is trying to solve. In the case of finding unique values, the developer should utilize a set data structure. In the other matter, such as determining whether two strings are anagrams to one another, developers should use the map data structure.

I hope you find this article helpful and enjoy reading it. Thank you for reading.

--

--

Osgood Gunawan

UX designer | Software Engineer | Dancer | ETL Developer | Data Migration. More about me : https://www.osgood1024.com/