Saturday, March 30, 2024

What are Maps in Javascript?

A Map in Javascript holds key-value pairs where the keys can be any datatype.

How to Create a Map?

We can create a map as shown below.

a) By passing an Array to new Map()

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

b) Create a Map and use Map.set()

const cities = new Map();

cities.set("Nagpur", "Nag");

cities.set("Mumbai", "Mum");

cities.set("Delhi", "Del");

What are avaialble Map methods?

1) new Map() : Creates a new Map object

2) set() : Sets the value for a key in a Map

ex: cities.set("Kolkata", Kol);

3) get() : Gets the value for a key in a Map

ex: cities.get("Kolkata");

4) clear() : Removes all the elements from a Map

5) delete() : Removes a Map element specified by a key

6) has() : Returns true if a key exists in a Map

7) forEach() : Invokes a callback for each key/value pair in a Map

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

cities.forEach (function(value, key) {

  let text = "";

  text += key + ' = ' + value 

  console.log(text);

})

Output:

Nagpur = Nag

Mumbai = Mum

Delhi = Del

8) entries() : Returns an iterator object with the [key, value] pairs in a Map

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

for (const x of cities.entries()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

Nagpur,Nag

Mumbai,Mum

Delhi,Del

9) keys() : Returns an iterator object with the keys in a Map

// Create a Map

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

for (const x of cities.keys()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

Nagpur

Mumbai

Delhi

10) values() : Returns an iterator object of the values in a Map

// Create a Map

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

for (const x of cities.values()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

Nag

Mum

Del

11) size : The size property returns the number of elements in a Map

ex: cities.size

No comments:

Post a Comment