Map in JavaScript

Map in JavaScript

A map is an object that holds key-value pairs, in the original insertion order of the keys. We can use any value(value of any type) as a key, and as valuable as well. To understand this, let’s take an informal example, which would give us an idea, about what are the key-value pairs here.

Map in JavaScript

Just consider that you have a gift store, and you want to store the selling price of all the products in the shop. So, simply what you can do is just write the product name, followed by a colon, and just write the selling price. (for example, “Teddy” : 1000), so here, the product name is some key, and the selling price is the value. Or let’s say that you want to have a record for how many units of each product you have in the store, so you can just take the product as the key, and the number of units as value.

Also, remember that using the key, you can get the value. This is like you are asking the selling price of the Teddy, and you get the value of 1000.

Let’s have a look at how can we create the Map object –

To create a map object, we just have to write something like this –

var SomeMap = new Map();

That’s it. The map object is created now. It is so simple. Also, there are a bunch of methods, that we can use for doing some different things with the Map object, and we are going to consider some of the methods over here, one by one. You can try writing the above instruction into the program and just create the Map object.