JavaScript Map()
The Map() Constructor
The Map() constructor creates Map objects.
A Map stores key-value pairs.
Unlike ordinary objects, Map keys can of any type (not only strings).
Syntax
new Map()
new Map(iterable)
Parameters
| Parameter | Description |
|---|---|
| iterable | Optional. An iterable object containing key-value pairs. |
Return Value
| Call | Returns |
|---|---|
new Map() |
A Map object |
new Map(iterable) |
A Map object initialized with entries |
Map is a genuine constructor.
It has no literal syntax.
Creating a Map
Creating a Map from Entries
Example
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
Try it Yourself »
Created From Iterables
The Map constructor accepts any iterable object.
Common iterables include:
- Arrays
- Strings
- Maps
- Sets
Map Keys
Map keys can be any JavaScript type (value).
| Key Type | Example |
|---|---|
| String | "name" |
| Number | 123 |
| Boolean | true |
| Object | {} |
| Function | myFunction |
Objects can be used as Map keys.
Example
const person = {name:"John"};
const map = new Map();
map.set(person, "Employee");
map.get(person); // "Employee"
Try it Yourself »
In the example above, the Map now contains one entry.
The key is the person object.
The value is the "Employee" string.
You can then retrieve the value by using the same object as the key:
Map vs Object
| Map | Object |
|---|---|
| Keys can be any value | Keys are strings or symbols |
| Maintains insertion order | Not designed primarily as a key-value collection |
Has a size property |
No built-in size property |
Note
Map objects are not the same as ordinary objects.
Use Map when you need a collection of key-value pairs.
Use Object when you need to describe an entity with named properties.
Common Properties and Methods
sizeset()get()has()delete()clear()keys()values()entries()forEach()
Learn More:
Iterable Information
Map objects are iterable.
A Map can be used in:
for...ofloopsArray.from()new Map(iterable)new Set(iterable)- Spread syntax (
...)
Object Hierarchy
Map objects inherit from Object.
Object └─ Map
Map() Questions
| Question | Answer |
|---|---|
| Constructor Type | Function |
| Creates | Map objects |
| Inherits From | Object |
| Iterable | Yes |
Related Map Pages:
Related Set Pages:
Browser Support
Map() is an ECMAScript6 (ES6 2015) feature.
JavaScript 2015 is supported in all browsers since June 2017:
| Chrome 51 |
Edge 15 |
Firefox 54 |
Safari 10 |
Opera 38 |
| May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |