Skip to main content

Command Palette

Search for a command to run...

Map and Set in Javascript

Updated
4 min read
Map and Set in Javascript

Hello readers,

Welcome to another blog on JS. In this blog, I'm going to cover the two most useful data types in JS: Map and Set. You can use these as alternatives to objects and arrays to enhance performance.

Before diving deep into the Map & Set, let's first know the issues with Objects & Arrays:

Problems with Objects

  1. Keys are only strings or symbols

  2. No order maintained

  3. No optimization at all.

  4. No easy way to get the length.

const obj = {};
obj[1] = "Number key";
obj["1"] = "String key";

console.log(obj); // output - { '1': 'String key' }
💡
Number (1) got converted to String("1") -- Data overwritten

Problems with Arrays

  1. Duplicates allowed

  2. Searching is slow

  3. Removing items is inefficient

const guests = ["Ranveer", "Ranveer"]; //Duplicates allowed

If you want a data type that removes these problems, then you should use Map or Set.

What is a map?

A map is also like Object which store values in key-value pairs, but with some extra powers.

It solves all the problems I've mentioned above about the Object.

Here is how you can enter values in a map:

const mapObj = new Map()

//syntax
mapObj.set(key, value)

//Example
mapObj.set("name", 'abhishek');

//acces the value
mapObj.get(name) //ouput - abhishek

Here,

  1. Map is a keyword to define a map object.

  2. mapObj.set() is a function of map to store the key-value pair.

  3. Key & value both can be any data type.

  4. mapObj.get(keyName) to get the value of the key.

Key features of Map

  1. Keys can be any data type

  2. Maintains insertion order

  3. Easy size access (mapObj.size)

  4. Built for frequent updates

Important points you should know about the map

  1. In a map, Objects are stored by reference, not value

    const map = new Map();
    
    map.set({}, "Object1");
    map.set({}, "Object2");
    
    console.log(map.size); // 2
    
  2. Iteration is clean and predictable

    for(let [key, value] of mapObj){
        console.log(key, value);
    }
    

What is Set?

A set is just like an array with extra powers, like:

  1. No duplicate values allowed

  2. Maintain insertino order

  3. Fast lookup (using has)

  4. No indexing like arrays

//initializing a set object
const set = new Set();

//add value
set.add({name: "abhishek"});
set.add({name: "abhishek"});
set.add(1);

//size of this set
set.size // output = 3
💡
Objects are stored by reference, not by value, so objects are not considered duplicates even if the key-value pairs are the same.

Useful methods

//add method to insert values
set.add(value);

//delete to remove value from set
set.delete(value);

//has to check value is available or not
set.has(value)

//size to get the size of the array
set.size

Map vs Object

Features Map Object
Key Types Any(object, number, etc) String or Symbol
Order Maintained Not maintained
Size map.size Manual (Object.keys(obj).length
Performance Better for frequent operations Not optimized
Iteration Easy Requires extra methods

Set vs Array

Feature Set Array
Duplicate Not allowed Allowed
Search Fast (using has) Slower (using includes or indexOf)
Order Maintained Maintained
Indexing No Yes

When to use Map

  • You need key-value pairs

  • Keys are not just strings

  • Frequent add/remove operations

  • Need ordered data

When to use Set

  • Removing duplicates

  • You want unique values only

  • Fast existence check

Real-life use case of a map and a set

  1. Removing Duplicates (set)

  2. Caching data (map)

  3. Tracking visited items (set)

That's it for this blog. I hope it has clarified any doubts you had about maps and sets. After reading this, you should be able to choose the best data type for your task. I'll see you in another blog.

Until then... Stay consistent & keep grinding

Peace ✌️