Thursday, January 9, 2025
Google search engine
HomeLanguagesJavascriptSet vs Map in JavaScript

Set vs Map in JavaScript

In JavaScript, Set and Map are two types of objects that are used for storing data in an ordered manner. Both these data structures are used to store distinct types of data inside the same object. In Maps, the data is stored as a key-value pair whereas in Set data is a single collection of values that are unique.

Let’s learn about the uses of these two data structures.

JavaScript Set: It is a collection of values that can be accessed without a specific key. The elements are unique and the addition of duplicates is not allowed. Sets are mostly used to remove duplicates from any other data structure

Syntax:

new Set([it]);

Example: In this example, we will learn how to implement a set

Javascript




let sample = new Set();
sample.add("Hello");
sample.add(1)
sample.add("Bye")
sample.add("@");
 
for (let item of sample) {
    console.log(item);
    }


Output:

Hello
1
Bye
@

JavaScript Map: Maps are used to store data in key-value pairs where keys are used to uniquely identify an element and values contain the data associated with it.

Syntax:

new Map([it])

Example: In this example, we will implement a map.

Javascript




let sample = new Map();
sample.set("name", "Ram");
sample.set("Role", "SDE")
sample.set("Country", "India")
 
for (let item of sample) {
    console.log(item);
    }


Output:

["name","Ram"]
["Role","SDE"]
["Country","India"]

What to use?

Choosing one data structure among these two depends on the usage and how we want to access the data. If we want the data to be identified by a key then we should opt for maps but if we want unique values to be stored then we should use a set.

Map Set
It is a collection of key-value It is a collection of unique elements
Map is two-dimensional The set is one dimensional
Values are accessed using keys In-built methods are used to access  values
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments