Software Development

Set vs Map in JavaScript

Set vs Map in JavaScript
Written by admin


Enhance Article

Save Article

Like Article

Enhance Article

Save Article

In JavaScript, Set and Map are two forms of objects which can be used for storing information in an ordered method. Each these information buildings are used to retailer distinct forms of information inside the identical object. In Maps, the info is saved as a key-value pair whereas in Set information is a single assortment of values which can be distinctive.

Let’s study in regards to the makes use of of those two information buildings.

JavaScript Set: It’s a assortment of values that may be accessed with out a particular key. The weather are distinctive and the addition of duplicates isn’t allowed. Units are largely used to take away duplicates from every other information construction

 

 

Syntax:

new Set([it]);

Instance: On this instance, we’ll learn to implement a set

Javascript

var pattern = new Set();

pattern.add("Whats up");

pattern.add(1)

pattern.add("Bye")

pattern.add("@");

  

for (var merchandise of pattern) {

    console.log(merchandise);

    }

Output:

Whats up
1
Bye
@

JavaScript Map: Maps are used to retailer information in key-value pairs the place keys are used to uniquely determine a component and values comprise the info related to it.

Syntax:

new Map([it])

Instance: On this instance, we’ll implement a map.

Javascript

var pattern = new Map();

pattern.set("title", "Ram");

pattern.set("Function", "SDE")

pattern.set("Nation", "India")

  

for (var merchandise of pattern) {

    console.log(merchandise);

    }

Output:

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

What to make use of?

Selecting one information construction amongst these two will depend on the utilization and the way we wish to entry the info. If we would like the info to be recognized by a key then we must always go for maps but when we would like distinctive values to be saved then we must always use a set.

Map Set
It’s a assortment of key-value It’s a assortment of distinctive components
Map is two-dimensional The set is one dimensional
Values are accessed utilizing keys In-built strategies are used to entry  values

About the author

admin

Leave a Comment