Map() constructor
The Map() constructor creates Map objects.
Syntax
new Map() new Map(iterable)
Note: Map() can only be constructed with new. Attempting to call it without new throws a TypeError.
Parameters
iterable Optional - An Array or other iterable object whose elements are key-value pairs. (For example, arrays with two elements, such as [[ 1, 'one' ],[ 2, 'two' ]].) Each key-value pair is added to the new Map.Examples:
const myMap = new Map([ [1, "one"], [2, "two"], [3, "three"], ]);
“Map() constructor - JavaScript | MDN” (MDN Web Docs). Retrieved May 8, 2024.
Map.groupBy() static method
The Map.groupBy() static method groups the elements of a given iterable using the values returned by a provided callback function. The final returned Map uses the unique values from the test function as keys, which can be used to get the array of elements in each group.
The method is primarily useful when grouping elements that are associated with an object, and in particular when that object might change over time. If the object is invariant, you might instead represent it using a string, and group elements with Object.groupBy().
Syntax
Map.groupBy(items, callbackFn)
Parameters
items - An iterable (such as an Array) whose elements will be grouped.
callbackFn - A function to execute for each element in the iterable. It should return a value (object or primitive) indicating the group of the current element. The function is called with the following arguments:
element - The current element being processed.index - The index of the current element being processed.Return value
A Map object with keys for each group, each assigned to an array containing the elements of the associated group.
Example:
First we define an array containing objects representing an inventory of different foodstuffs. Each food has a type and a quantity.
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 9 },
{ name: "bananas", type: "fruit", quantity: 5 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 12 },
{ name: "fish", type: "meat", quantity: 22 },
];The code below uses Map.groupBy() with an arrow function that returns the object keys named restock or sufficient, depending on whether the element has quantity < 6. The returned result object is a Map so we need to call get() with the key to obtain the array.
const restock = { restock: true };
const sufficient = { restock: false };
const result = Map.groupBy(inventory, ({ quantity }) =>
quantity < 6 ? restock : sufficient,
);
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]The key to a Map can be modified and still used. However you can’t recreate the key and still use it. For this reason it is important that anything that needs to use the map keeps a reference to its keys.
// The key can be modified and still used
restock["fast"] = true;
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
// A new key can't be used, even if it has the same structure!
const restock2 = { restock: true };
console.log(result.get(restock2)); // undefined“Map.groupBy() - JavaScript | MDN” (MDN Web Docs). Retrieved May 14, 2024.
Map.prototype[@@iterator]() method
The [@@iterator]() method of Map instances implements the iterable protocol and allows Map objects to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns a map iterator object that yields the key-value pairs of the map in insertion order.
The initial value of this property is the same function object as the initial value of the Map.prototype.entries property.
Syntax
map[Symbol.iterator]()
Parameters
None.
Return value
The same return value as Map.prototype.entries: a new iterable iterator object that yields the key-value pairs of the map.
Examples:
Iteration using for...of loop
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const entry of myMap) {
console.log(entry);
}
// ["0", "foo"]
// [1, "bar"]
// [{}, "baz"]
for (const [key, value] of myMap) {
console.log(`${key}: ${value}`);
}
// 0: foo
// 1: bar
// [Object]: bazManually hand-rolling the iterator
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
const mapIter = myMap[Symbol.iterator]();
console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]“Map.prototype[@@iterator]() - JavaScript | MDN” (MDN Web Docs). Retrieved May 27, 2024.
Map.prototype.clear() method
The clear() method of Map instances removes all elements from this map.
Syntax
clear()
Parameters
None.
Return value
None (undefined).
Examples:
const myMap = new Map();
myMap.set("bar", "baz");
myMap.set(1, "foo");
console.log(myMap.size); // 2
console.log(myMap.has("bar")); // true
myMap.clear();
console.log(myMap.size); // 0
console.log(myMap.has("bar")); // false“Map.prototype.clear() - JavaScript | MDN” (MDN Web Docs). Retrieved May 27, 2024.
Map.prototype.delete() method
The delete() method of Map instances removes the specified element from this map by key.
Syntax
mapInstance.delete(key)
Parameters
key - The key of the element to remove from the Map object.Return valuetrue if an element in the Map object existed and has been removed, or false if the element does not exist.
Examples
const myMap = new Map();
myMap.set("bar", "foo");
console.log(myMap.delete("bar")); // Returns true. Successfully removed.
console.log(myMap.has("bar")); // Returns false. The "bar" element is no longer present.“Map.prototype.delete() - JavaScript | MDN” (MDN Web Docs). Retrieved May 28, 2024.
Map.prototype.entries() method
The entries() method of Map instances returns a new map iterator object that contains the [key, value] pairs for each element in this map in insertion order.
Syntax
entries()
Parameters
None.
Return value
A new iterable iterator object.
Examples:
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
const mapIter = myMap.entries();
console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]“Map.prototype.entries() - JavaScript | MDN” (MDN Web Docs). Retrieved May 28, 2024.
Map.prototype.forEach() method
The forEach() method of Map instances executes a provided function once per each key/value pair in this map, in insertion order.
Syntax
forEach(callbackFn) forEach(callbackFn, thisArg)
Parameters
callbackFn - A function to execute for each entry in the map. The function is called with the following arguments:
* value - Value of each iteration.
* key - Key of each iteration.
* map - The map being iterated.
thisArg Optional - A value to use as this when executing callbackFn.
Return value
None (undefined).
Examples:
function logMapElements(value, key, map) {
console.log(`map.get('${key}') = ${value}`);
}
new Map([
["foo", 3],
["bar", {}],
["baz", undefined],
]).forEach(logMapElements);
// Logs:
// "map.get('foo') = 3"
// "map.get('bar') = [object Object]"
// "map.get('baz') = undefined"“Map.prototype.forEach() - JavaScript | MDN” (MDN Web Docs). Retrieved May 28, 2024.
Map.prototype.get() method
The get() method of Map instances returns a specified element from this map. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map object.
Syntax
get(key)
Parameters
key - The key of the element to return from the Map object.Return value
The element associated with the specified key, or undefined if the key can’t be found in the Map object.
Examples:
const myMap = new Map();
myMap.set("bar", "foo");
console.log(myMap.get("bar")); // Returns "foo"
console.log(myMap.get("baz")); // Returns undefinedUsing get() to retrieve a reference to an object
const arr = [];
const myMap = new Map();
myMap.set("bar", arr);
myMap.get("bar").push("foo");
console.log(arr); // ["foo"]
console.log(myMap.get("bar")); // ["foo"]“Map.prototype.get() - JavaScript | MDN” (MDN Web Docs). Retrieved May 29, 2024.
Map.prototype.has() method
The has() method of Map instances returns a boolean indicating whether an element with the specified key exists in this map or not.
Syntax
has(key)
Parameterskey - The key of the element to test for presence in the Map object.
Return valuetrue if an element with the specified key exists in the Map object; otherwise false.
Examples
const myMap = new Map();
myMap.set("bar", "foo");
console.log(myMap.has("bar")); // true
console.log(myMap.has("baz")); // false“Map.prototype.has() - JavaScript | MDN” (MDN Web Docs). Retrieved May 29, 2024.
Map.prototype.keys() method
The keys() method of Map instances returns a new map iterator object that contains the keys for each element in this map in insertion order.
Syntax
keys()
Parameters
None.
Return value
A new iterable iterator object.
Examples
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
const mapIter = myMap.keys();
console.log(mapIter.next().value); // "0"
console.log(mapIter.next().value); // 1
console.log(mapIter.next().value); // {}“Map.prototype.keys() - JavaScript | MDN” (MDN Web Docs). Retrieved May 29, 2024.
Map.prototype.set() method
The set() method of Map instances adds or updates an entry in this map with a specified key and a value.
Syntax
set(key, value)
Parameters
key - The key of the element to add to the Map object. The key may be any JavaScript type (any primitive value or any type of JavaScript object).value - The value of the element to add to the Map object. The value may be any JavaScript type (any primitive value or any type of JavaScript object).Return value
The Map object.
Examples
const myMap = new Map();
// Add new elements to the map
myMap.set("bar", "foo");
myMap.set(1, "foobar");
// Update an element in the map
myMap.set("bar", "baz");Using the set() with chaining
// Add new elements to the map with chaining.
myMap.set("bar", "foo").set(1, "foobar").set(2, "baz");“Map.prototype.set() - JavaScript | MDN” (MDN Web Docs). Retrieved May 31, 2024.
Map.prototype.values() method
The values() method of Map instances returns a new map iterator object that contains the values for each element in this map in insertion order.
Syntax
values()
Parameters
None.
Return value
A new iterable iterator object.
Examples
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
const mapIter = myMap.values();
console.log(mapIter.next().value); // "foo"
console.log(mapIter.next().value); // "bar"
console.log(mapIter.next().value); // "baz"“Map.prototype.values() - JavaScript | MDN” (MDN Web Docs). Retrieved May 31, 2024.
Map.prototype.size property
The size accessor property of Map instances returns the number of elements in this map.
Examples
const myMap = new Map();
myMap.set("a", "alpha");
myMap.set("b", "beta");
myMap.set("g", "gamma");
console.log(myMap.size); // 3“Map.prototype.size - JavaScript | MDN” (MDN Web Docs). Retrieved May 31, 2024.