Map And Set in Javascript


Namaste!, this is Aryan Sharma's blog, and I hope you're all doing well & great.
Welcome to another blog of this JavaScript course.
πYou can find my blogshereβοΈ
Let's get started!
Map
The map is a collection of key-value pairs, just like an Object
.
But the main difference is that Map
allows keys of any type, not only numeral data (numbers).
Map Methods
new Map()
β creates the map.
map.set(key, value)
β stores the value by the key.map.get(key)
β returns the value by the key,undefined
ifkey
doesnβt exist in map.map.has(key)
β returnstrue
if thekey
exists,false
otherwise.map.delete(key)
β removes the element (the key/value pair) by the key.map.clear()
β removes everything from the map.map.size
β returns the current element count.
Iteration on Map
there are 3 methods:
map.keys()
β returns an iterable for keys.map.values()
β returns an iterable for values.
Example:
let obj = {
name: "Aryan",
age: 19
};
let map = new Map(Object.entries(obj));
alert( map.get('name') ); // Aryan
Set
A Set
is a special type of collection - where each value is unique;
Set Methods
set.add(value)
β adds a value, and returns the set.set.delete(value)
β removes the value, returnstrue
ifvalue
existed at the moment, otherwisefalse
.set.has(value)
β returnstrue
if the value exists.set.clear()
β removes everything from the set.set.size
β element count.
Iteration on Set
let set = new Set(["oranges", "apples", "bananas"]);
for (let value of set) alert(value);
// the same with forEach:
set.forEach((value, valueAgain, set) => {
alert(value);
});
Siuuu in the next blog...Stay tunedπΆ
Subscribe to my newsletter
Read articles from aryan sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

aryan sharma
aryan sharma
Hey, Awesome ones! Aryan this sideπ Full-Stack Developer, Life-Long Learner, Optimistic Using this blog to help code newbies. Learn with me! :)