Skip to main content

Command Palette

Search for a command to run...

Maps & Sets: The Modern Way to Store Data

Updated
5 min read

What are we gonna Study?

Hey there folks, hope you are doing great in your life, today we are going to understand what are maps and sets in JavaScript. The following are the topics for today:

  1. What Map is

  2. What Set is

  3. Difference between Map and Object

  4. Difference between Set and Array

  5. When to use Map and Set

These are really very fun just bear with me with all of your focus along with a tea/coffee and dive into the world of sets and maps :)


What is Map?

First of all, don't think about google maps or paper maps, They are different maps :)

So, basically maps in javascript are just key-value pairs... Yes, they are key-value pairs just like an object (we'll talk about the differences just wait and watch)

const character = new Map();

character.set("name", "Naruto Uzumaki");
character.set("age", 17);
character.set("village", "Konoha");
character.set("friends", ["Sasuke", "Sakura", "Gaara", "Shikamaru"]);

console.log(character.get("name")); // Output: Naruto Uzumaki
console.log(character.get("age")); // Output: 17
console.log(character.get("village")); // Output: Konoha
console.log(character.get("friends")); // Output: [ 'Sasuke', 'Sakura', 'Gaara', 'Shikamaru' ]

Understanding a bit? I hope so you are, because this blog is about the concept not the methods of maps and sets, you've to discover them on your own :)


Map VS Object

They look same but there are some differneces let's talk about them

Parameter Map Object
Key Type The key can be anything form primitives, objects, and even functions. Only strings and symbols can be the key.
Size There is a size property in maps, which allows you to get the total length of the map (just like length in arrays). There isn't any size or length property, you have to make your own logic for counting.
Iteration Maps are iterables, which means they can be iterated directly. Objects aren't iterable which means they can't be iterated directly, for...of loop can't be implemented directly.
Performance Maps are highly optimized for insertion and deletion, that is why we use them when we have to make in-memory DB. Objects aren't optimized for insertions and deletions.
Serialization & Parsing No native support for serialization & parsing (but you can build support on your own). Native support for serialization & parsing due to JSON.stringify() & JSON.parse().
Security Safe to use with user-provided keys and values. Generally, not safer, because it is vulnerable to hackers.

Now, there are 2 more differences but come on i am not spoon-feeding you, go ahead to MDN Docs and read them too!

That's an assignment!


What are Sets?

Sets are the collection of unique data. It is almost as same as arrays but still there is a difference of 19 lakh and 20 lakh (we'll discuss that too)

const strongest = new Set();

strongest.add("Son Goku");
strongest.add("Saitama");
strongest.add("Alien X");

console.log(strongest.has("Son Goku")); // true
console.log(strongest.size); // 3

See, this is working just like an array the only difference is that the keywords are different.


Set VS Array

Here is a comprehensive table that would help you understand the difference between the two

Parameter Set Array
Uniqueness Unique Values by default No guaranteed unique values, you have to manually make it unique if you want to
Accessing Elements No direct access using indexes, usually accessed via iteration or specific methods. Elements can be accessed by index.
Size To get the size, you have to use .size property. .length is used.
Performance The .has() method is generally considered faster, making the process of checking a particular element faster. Faster for accessing values due to indexes, instead of iterations and looping.

When to Use Maps & Sets?

The use case depends entirely on you, but still I'll tell some of my use cases.

Maps

  • Use when insertion and deletion are the top priority.

  • One practical use case is In-Memory DB.

Sets

  • Use when uniqueness is the top priority.

  • You can also use it like const arr = [...mySet] so that you can make a new array which is unique (At least, I use it this way :) )


Wrap Up!

So, that was it from my side today, we learned about maps and sets again methods are your reponsibility, I was here for the concepts :)

I'll catch you in the next blog until then keep coding and enjoying your tea/coffee ☕💝

JavaScript: Everything you should know

Part 21 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

Biggest Mystery Solved: Spread vs Rest Operators

What are we gonna Study? Hey there folks, hope you are doing great in your day to day coding life, let's gather some new knowledge together :) The topics for today are: What spread operator does Wha

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!