Open In App

What is JavaScript Map and how to use it ?

What is Map?

It is an object which holds the key-value pair. It is a collection of elements in which elements are present in key-value pairs. Map remembers the original order of insertions of keys. The key and value in the map could be any object and primitive values. It is provided by ES6. It gives the elements in the same order in which they have been inserted.

Syntax:



new Map( );
new Map( [iterable_objects] );

Return type: It returns a new map object.

Parameters: An array or iterable object.



Example: In this example of a Map it takes an iterable element as a parameter:




const company = new Map([
    ["name", "GFG"],
    ["no_of_employee", 200],
    ["category", "education"]
]);
function print(key, values) {
    console.log(values + "=>" + key);
}
company.forEach(print);

Output
name=>GFG
no_of_employee=>200
category=>education



Example: In this example of Map it returns an empty object.




const company = new Map();
company.set("name", "GFG");
company.set("no_of_employee", 200);
company.set("category", "education");
function print(key, values) {
    console.log(values + "=>" + key);
}
company.forEach(print);

Output
name=>GFG
no_of_employee=>200
category=>education



JavaScript Map Properties: 

A JavaScript property is a member of an object that associates a key with a value.

Instance Properties

Description

constructor It is used to return the constructor function of Map.
size Return the number of keys, and value pairs stored in a map.

JavaScript Map Methods: 

JavaScript methods are actions that can be performed on objects.

Static Methods

Description

clear( ) Removal of all the elements from a map and making it empty.
delete() Delete the specified element among all the elements which are present in the map.
entries( ) Returning an iterator object which contains all the [key, value] pairs of each element of the map.
forEach() The map with the given function executes the given function over each key-value pair.
get( ) Returning a specific element among all the elements which are present in a map.
has( ) Check whether an element with a specified key exists in a map or not.
keys() The keys from a given map object return the iterator object of keys.
set() Add key-value pairs to a Map object.
values() Return a new Iterator object that contains the value of each element present in the Map.

Article Tags :