JavaScript Map()
Syntax & Examples
Map constructor
The Map constructor in JavaScript creates a new Map object.
Syntax of Map
There are 2 variations for the syntax of Map() constructor. They are:
1.
new Map()This constructor creates a new Map object that is empty.
Returns value of type Map.
2.
new Map(iterable)Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
iterable | optional | An iterable (e.g., an array) whose elements are key-value pairs. Each key-value pair is added to the new Map object. |
This constructor creates a new Map object using given iterable.
Returns value of type Map.
✐ Examples
1 Creating an empty Map
In JavaScript, we can create an empty Map object using the Map constructor without any arguments.
For example,
- Create a new empty Map object using the
new Map()syntax. - Log the Map object to the console using
console.log().
JavaScript Program
const map = new Map();
console.log(map);Output
Map(0) {}2 Creating a Map from an iterable
In JavaScript, we can create a Map object from an iterable (e.g., an array) containing key-value pairs using the Map constructor.
For example,
- Create an array
itemscontaining key-value pairs. - Create a new Map object
mapusing thenew Map(iterable)syntax. - Log the Map object to the console using
console.log().
JavaScript Program
const items = [['a', 1], ['b', 2], ['c', 3]];
const map = new Map(items);
console.log(map);Output
Map(3) { 'a' => 1, 'b' => 2, 'c' => 3 }Summary
In this JavaScript tutorial, we learned about Map constructor of Map: the syntax and few working examples with output and detailed explanation for each example.