JavaScript – Map


What is a Map ?

A map is the representation of certain elements which are mapped with some values.

What is a Map in Javascript ?

A map is a javascript object used to map the keys with values.

Map stores each element in key-value pair.

Syntax :

new Map([iterable])  

Iterable:

It defines an array and other iterable object whose elements are in the form of key-value pair.


Example :

<script>
                        var map = new Map();
                        map.set("FName","Abdul");
                        map.set("LName","Kalaam");
                        map.set("Sex","Male");
                        map.set("Occupation","Scientist");
                        map.set("Location","India");
                        map.set("Language","Tamil");
                        console.log(map);
                </script>

Output :

Free online javascript course !!!

Click to Learn More about – Javascript online learning

How does map works in javascript ?

Map object cannot contain duplicate keys.

Map object can contain duplicate values.

Key-value pair can be of any type since it allows both object and primitive values.

Map object iterates its elements in insertion order.


Methods of Map Object

A map object is a collection of key-value pairs with some of the common methods listed below.

SnoMethods / FunctionDescription
1clear()clear() method removes all the elements from a Map object.
2delete()delete() method deletes the specified element from a Map object.
3entries()entries() method returns an object of Map iterator that contains the key-value pair for each element.
4forEach()forEach() method executes the specified function once for each key/value pair.
5get()get() method returns the value of the specified key.
6has()has() method indicates whether the map object contains the specified key element.
7keys()keys() method returns an object of Map iterator that contains the keys for each element.
8set()set() method adds or updates the key-value pairs to Map object.
9valuesvalues() method returns an object of Map iterator that contains the values for each element.