Skip to main content

Command Palette

Search for a command to run...

Map & Set in JavaScript

Updated
•5 min read•View as Markdown

Hello readers welcome to todays exciting blog, where we would be discussing about map and set and you shall be amazed to know how we generate efficiency of softwares with some simple use of Map and Set

What is Map ?

The Map object holds key-value pairs and remembers the original insertion order of the keys. Map is more powerful than objects.

If you were to refer MDN docs, you would read the following about Map:

Map objects are collections of key-value pairs. A key in the Map may only occur once; it is unique in the Map's collection.

Now it is a common point of confusion that a normal JS object does the same after all, it stores using key value pairs as well and the key in the object may only occur once, then why use Map at all?

When to use Map over Object

  1. Keys that are stored in JS object are kept as string or symbol only, making object keys as limited as they lose distinction. Map on the other hand uses === check for the keys. So the keys in maps are not saved as strings.
const a = new Map();
 a.set("1","Saurav");
 a.set(1, "Pratap");

const b = { "1":"Saurav", 1:"Pratap" };

 console.log(a);    //Map(2) {'1' => 'Saurav', 1 => 'Pratap'}
 console.log(b);    //{1: 'Pratap'}
  1. A Map does not contain any keys by default. It only contains what is explicitly put into it. On the other hand Object has prototype, so it contains default keys that could collide with your own keys if you're not careful.

  2. The number of items in a Map is easily retrieved from its size property. But it isn't a straight forward job with objects, where you need to convert it to an array and then find the no. of keys in it which would determine the length of it.

const newMap = new Map();
newMap.set(1,"Saurav");

newMap.size //1

const newObj = {1:"Saurav"}
Object.keys(newObj).length //1
  1. Map is designed to be performant for frequent addition and deletion of key value pairs, which is not the case for objects.

  2. There is no native support for serialization or parsing in case of maps, which is possible for objects.

What is Set ?

A set is a collection of unique values only. No duplicates are allowed in a set. You can iterate through the elements of a set in insertion order.

const set = new Set();

set.add(1);
set.add(2);
set.add(2);

console.log(set); // {1, 2}

When to use Set over Arrays

  1. Arrays allow duplicates so there is no built in uniqueness and we would need extra logic to remove duplicates.
const arr =[1,2,3,2] //duplicate elements are allowed
const mySet1 = new Set();

mySet1.add(1); // Set(1) { 1 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add(5); // Set(2) { 1, 5 }
  1. When you want to know if an element is present or not in the array, you need to use includes() which is linear searching which makes it inefficient compared to searching for the presence of an element inside the set itself which uses the has() method
mySet1.has(5) //true

Set provides near constant-time lookup (O(1)) using hashing, while arrays require linear search (O(n)).

Mistakes while using Map & Set

There are chances that you might be using Map and set for the first time and they look similar to arrays and objects, however they are different and we would be discussing the common mistakes that you might do.

  1. Using Set as array
    Sets are not indexed like arrays, hence trying to get value through index shall give undefined.
const set = new Set([1, 2, 3]);
console.log(set[0]); // undefined
const key = {};
map.set(key, "value stored");

console.log(map.get(key)); // value store
  1. Confusing between using .length and .size: You might use .length with map and set to find out the number of elements that they contain, it would give undefined, because map and set use the .size method to provide the no. of elements within them.

  2. Forgetting to convert Set into array: Suppose you want to do some manipulation on the elements of the array, you need to first convert it into array before doing any operation.

const unique = new Set([1, 2, 2, 3]);
console.log(unique.map(x => x * 2)); // error
const result = [...unique].map(x => x * 2); // ✅ correct way
  1. Using Bracket Notation with Map
const map = new Map();
map["name"] = "Saurav"; //  WRONG
console.log(map.get("name")); // undefined
console.log(map.has("name")); // false
console.log(map) //Map(0) { name: 'Saurav' }

this is not the right way to put elements in a map, this is simply using the generic property of object to insert elements. The right way to put elements into the map would be to use set() .

const map = new Map();
map.set("name","Saurav")
console.log(map.get("name")); // Saurav
console.log(map.has("name")); //true
  1. Treating map like an object
const map = new Map()

map["name"] = "Saurav";
map["phone"] = "990";

for(let key in map) {
  console.log(key, map[key])
}

console.log("***************************")
map.set("name","Pratap");
map.set("address","BBS")

for(let [key, value] of map) {
  console.log(key, value);
}
name Saurav
phone 990 
***************************
name Pratap 
address BBS

You see the output for the above code block, see when you want to iterate over the elements of the map, you should not treat it like an object, but if you have inserted the element into it like an object itself, then you shall get the value, which is the wrong way to do it, as discussed in the point before.

Conclusion

This was all about set and map, you could use them as a good alternative for array where you don't need duplication and for objects where you need to do frequent lookups, it improves the system, but remember not every problem needs to be solved using map and set itself.