What is JavaScript Map and how to use it ?
What is Map?
A Map in JavaScript is a collection of key-value pairs where keys can be any data type. Unlike objects, keys in a Map maintain insertion order. It provides methods to set, get, delete, and iterate over elements efficiently, making it useful for data storage and retrieval tasks.
Syntax
new Map( );
new Map( [iterable_objects] );
Return type: It returns a new map object.
Parameters: An array or iterable object.
Example: Creating and Using a Map
In this example we creates a Map named company with key-value pairs. The print function logs each value followed by its corresponding key using company.forEach(print).
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: Iterating Over a Map Using forEach()
In this example we creates a Map named company and populates it with key-value pairs. The print function logs each value followed by its corresponding key using company.forEach(print).
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: An instance property is a property that has a new copy for every new instance of the class.
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.
- Instance Methods: If the method is called on the instance of a Map then it is called an instance method of Map.
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. |