JavaScript Map()
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)
Map is a genuine constructor.
It has no literal syntax.
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 |
Creating a Map
Example
const fruits = new Map();
Creating a Map from Entries
Example
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
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 value.
| Key Type | Example |
|---|---|
| String | "name" |
| Number | 123 |
| Boolean | true |
| Object | {} |
| Function | myFunction |
Example
const person = {name:"John"};
const map = new Map();
map.set(person, "Employee");
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 |
Common Properties and Methods
sizeset()get()has()delete()clear()keys()values()entries()forEach()
Object Hierarchy
Map objects inherit from Object.
Object └─ Map
| What | Value |
|---|---|
| Constructor Type | Function |
| Creates | Map objects |
| Inherits From | Object |
| Iterable | Yes |
Iterable Information
Map objects are iterable.
A Map can be used in:
for...ofloopsArray.from()new Map(iterable)new Set(iterable)- Spread syntax (
...)
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.
Browser Support
new 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 |