Map And Set in Javascript

Map And Set in Javascript

·

2 min read

namaste-welcome.gif (498Ă—341)

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 if key doesn’t exist in map.

  • map.has(key) – returns true if the key 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, returns true if value existed at the moment, otherwise false.

  • set.has(value) – returns true 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🎶

Don't forget to follow me on Twitter And LinkedIn

Â