JavaScript Maps
How to Create a Map
You can create a JavaScript Map by:
- Passing an array to new Map()
- Creating a Map and using Map.set()
The new Map() Method
You can create a Map by passing an array to the new Map() constructor:
Example
// Create a Mapconst inventory = new Map([ ["apples", 500], ["bananas", 300], ["grapes", 200]]);
The set() Method
You can add elements to a Map with the set() method:
Example
// Create a Mapconst inventory = new Map();// Set Map Valuesinventory.set("apples", 500);inventory.set("bananas", 300);inventory.set("grapes", 200);
The set() method can also be used to change existing Map values:
Example
inventory.set("apples", 200);
The get() Method
The get() method retrieves the value of a key in a Map:
Example
inventory.get("apples"); // Returns 500
Maps are Objects
The typeof operator returns "object" for Maps:
Example
// Returns "object":typeof inventory;
The instanceof operator returns true when checking if an object is an instance of Map:
Example
// Returns true:inventory instanceof Map;
JavaScript Objects vs. Maps
Differences between JavaScript Objects and Maps:
Feature
Object
Map
Iterability
Not directly iterable
Directly iterable
Size Property
Do not have a size property
Have a size property
Key Types
Keys must be Strings or Symbols
Keys can be any datatype
Key Order
Keys are not well ordered
Keys are ordered by insertion
Default Keys
Have default keys
Do not have default keys
Complete Map Reference
For a complete reference, visit the Complete JavaScript Map Reference. The reference contains descriptions and examples of all Map properties and methods.
Browser Support
Map is an ES6 feature (JavaScript 2015).
ES6 is fully supported in all modern browsers since June 2017:
Browser
Version
Chrome
51 (May 2016)
Edge
15 (Apr 2017)
Firefox
54 (Jun 2017)
Safari
10 (Sep 2016)
Opera
38 (Jun 2016)
Map is not supported in Internet Explorer.