Set and Map in Javascript.


Set
Collection of elements that store unique elements.
A set of special type collections- a set of values, where each value may occur only once.
var set1 = new Set([10, 20, 30, 30, 40, 40]);
//it contains [10, 20, 30 ,40]
To add more values to set
var set1 = new Set([10, 20, 30, 30, 40, 40]);
set1.add(70);
console.log(set1);
let a = [1, 2, 1, 2, 1, 2, 8, 1, 9];
let num = new Set (a);
num.add(5);
console.log(num);
Properties:
new.Set([it])-//create set //it-iterable
Set.prototype.add(value)-//add value, return the set itself.
Set.delete(value) //remove value
Set.has(value) //return true if value exist
Set.size(value) //element count
Map
Map is a collection of keyed data items, just like an object but the difference is that map allow keys of any type.
Map is a collection of elements where each element is stored as a Key, value pair. You create your key whatever data type you want.
let city = [
['india', 'delhi'],
['gujrat', 'surat'],
['rajisthan', 'jaipur']
];
let newmap = new Map(city);
console.log(newmap);
console.log(newmap.get('india'));
Properties
new Map([it]) //create map
map.set(key, value) //store value by key
map.has(key) //return true if key exist
map.size //return current element count
map.get(key) //return val by key, undef if key does'nt exist in map.
Subscribe to my newsletter
Read articles from Vikas Taliyan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Vikas Taliyan
Vikas Taliyan
Hello, As a Frontend Web Developer(Fresher), I bring a unique blend of technical skills and creativity to the table. With an eye for detail and a passion for user experience, I am dedicated to creating visually stunning and engaging websites and applications. My skills in HTML, CSS, JavaScript, and various frontend frameworks such as React and Angular allow me to design and implement innovative solutions that meet the needs of modern businesses. I love reading and writing Technical blogs and helping out the community.