Skip to main content

Command Palette

Search for a command to run...

Map and Set in JavaScript

Updated
2 min readView as Markdown
Map and Set in JavaScript

Map and Set are the modern feauture of JavaScript comes in ES6

What is map ?

Map is a collection of key-value pairs just like objects but it has some special powers that made it more powerful and useful than the objects
It is a built-in Data Structure in JavaScript

const map = new Map();

map.set("fname", "Prashant");
map.set("lname", "Chandel");
map.set("role", "developer");

console.log(map.get("name")); // "Nawazish"
console.log(map.size);        // 3

Map methods

.set()

map.set() allows you to insert values in map, It takes two arguments one is key and the other one is value

const map = new Map();

map.set("name", "Prashant");

console.log(map.get("name"));

.get()

map.get() is used to take value from the map

const map = new Map();

map.set("name", "Prashant");

console.log(map.get("name"));

.size

map.size is the property that tell us about the total size of key-value pairs

const map = new Map();

map.set("fname", "Prashant");
map.set("lname", "Chandel");
map.set("role", "developer");

console.log(map.get("name")); // "Nawazish"
console.log(map.size);        // 3

Defference Between map and Object

What is Set ?

set let you store unique values weather they are primitive or non-primitive datatypes, These are same as in maths we have sets

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

Some Basic methods of set

.add()

used to insert a value in set

strongest.add("Son Goku");

.has()

it checks weather a value is present in the set or not, it returns a boolean

const strongest = new Set();

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

console.log(strongest.has("Son Goku"));

.size

It is same as the size in the map,Here it tells that how many elements are there in a set

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

Difference Between Sets and Array

When to use Map and Set

Map:

  • When insertion & deletion is the priority

  • It is also used to make In-Memory DB

Set:

  • It is used when we don't want to store duplicate values

  • Also by this we can use hash-based lookup

Conclusion:

In summary, Both Set and Map are the upgraded version of Array and Objects
It depends upon our usecase when we use map or object.

21 views