Map() Constructor
The Map()
constructor in JavaScript creates a new Map
object. A Map
holds key-value pairs, where keys can be of any type. The insertion order of elements is preserved, and it provides efficient lookup, addition, and deletion operations.
Syntax
new Map()
new Map(iterable)
Parameters
Parameter | Description |
---|---|
iterable | An iterable object (such as an array) containing key-value pairs (arrays of length 2). If no iterable is provided, an empty Map is created. |
Return Value
The new Map()
constructor returns a new Map
object containing the key-value pairs from the provided iterable or an empty map if no iterable is given.
Examples
1. Creating an Empty Map
The following example creates an empty Map
and then adds key-value pairs using the set()
method.
const myMap = new Map();
myMap.set('name', 'Arjun');
myMap.set('age', 25);
console.log(myMap);
Output
Map(2) { 'name' => 'Arjun', 'age' => 25 }
new Map()
creates an empty map.set()
method is used to add key-value pairs.
2. Initializing a Map with an Iterable
You can initialize a Map
with an array of key-value pairs.
const userMap = new Map([
['name', 'Bob'],
['age', 30],
['city', 'New York']
]);
console.log(userMap);
Output
Map(3) { 'name' => 'Bob', 'age' => 30, 'city' => 'New York' }
- The
new Map(iterable)
constructor initializes theMap
with pre-defined key-value pairs. - Each pair is stored as an entry in the
Map
.
3. Using Objects as Keys
The Map
object allows keys of any type, including objects.
const objKey = { id: 1 };
const myMap = new Map();
myMap.set(objKey, 'apple');
console.log(myMap.get(objKey));
Output
apple
Maps allow objects as keys, unlike regular objects where keys are always converted to strings.
4. Checking Map Size
The size
property returns the number of key-value pairs in a Map
.
const fruitMap = new Map([
['apple', 10],
['banana', 5],
['cherry', 7]
]);
console.log(fruitMap.size);
Output
3
5. Iterating Over a Map
The forEach()
method can iterate over the entries of a Map
.
const myMap = new Map([
['name', 'Arjun'],
['age', 25]
]);
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
Output
name: Arjun
age: 25
Each key-value pair is processed in the order it was inserted.