What topics we are going to cover?

  1. What are Maps?
  2. What are the methods used in it and how we can insert or retrieve values to it?
  3. How Maps works, behave with loops and what is happening behind the scenes?

What are Maps?

By the word Map, here I mean another new method which is being used these days in modern JavaScript. Here we are going to see the classic dataType of Map. Mostly Map is getting used in looping concepts that’s a great thing, but if you go directly for all those then you won’t be able to understand the classic dataType of Map.

So let’s fire up our code editor and understand the concepts of Map with some amazing examples.

var myMap = new Map();

This is almost kind of constructional approach, where we create an object from prototype and stuff like that.

What are the methods used in Maps?

Now Map has a lot of properties and I think you should take a look at it, at once. So whenever you gonna type myMap. then you can see a list of methods will be appearing on your screen like- get, set, forEach, values, and bunch of things. So one of the common methods which are being used widely is set and get method and by this time I guess from its name itself you might have guessed it like these are some default setters and getters means it can add values to them and retrieve values from them.

How to insert values in Maps?

Let’s go ahead and try with set() method and have some of the fun together:

Note: They work almost like objects but remember this, Maps are not like objects, they are completely different.

var myMap = new Map();
myMap.set(1, "Ricky"); //myMap.set(any key, any value)
myMap.set(2, "Monty"); //myMap.set(any key, any value)
myMap.set(3, "Henna"); //myMap.set(any key, any value)
myMap.set(4, "Monta"); //myMap.set(any key, any value)
console.log(myMap);

Now if you try to run this code in your editor, then you gonna see an output like this on your screen.

Map(4) { 1 => 'Ricky', 2 => 'Monty', 3 => 'Henna', 4 => 'Monta' }

Notice here, how Maps by default itself is telling you that how many properties you are storing in it and one more thing you can see here they have used => these arrow between its key, value pair to differentiate, and make you understand that they are not your regular objects.

#javascript-development #maps #array-methods #arrays #javascript

Maps in JavaScript
1.50 GEEK