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 Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Vikas Kumar
Vikas Kumar
As a Frontend Web Developer, I bring a unique blend of technical expertise and creative vision to design and implement robust web applications. My proficiency in core web technologies including HTML, CSS, and JavaScript, combined with hands-on experience in React and NodeJs, allows me to deliver high-performance, responsive, and intuitive user interfaces. I am also dedicated to continuous learning and community engagement, regularly publishing technical blogs to share insights and foster collaborative growth.