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);
});