JavaScript Map
- Previous Page JS Set Methods
- Next Page JS Map Methods
Map is a collection of key-value pairs, where the key can be any data type.
Map will remember the original insertion order of keys.
How to create Map
You can create JavaScript Map in the following ways:
- Pass an array to
new Map()
. - Create a Map and use
Map.set()
.
new Map() method
You can pass an array to new Map()
Constructor to create Map:
Instance
// Create a Map const fruits = new Map([ ["apples", 500], ["bananas", 300], ]
set() method
You can use set()
Method to add elements to Map:
Instance
// Create a Map const fruits = new Map(); // Set Map value fruits.set("apples", 500); fruits.set("bananas", 300); fruits.set("oranges", 200);
set()
The method can also be used to change the existing Map value:
Instance
fruits.set("apples", 200);
get() method
get()
Method to get the value of the key in Map:
Instance
fruits.get("apples"); // Returns 500
Map is an object
typeof
Returns object:
Instance
// Returns object: typeof fruits;
instanceof Map
Returns true:
Instance
// Returns true: fruits instanceof Map;
The difference between JavaScript objects and Map
The following is the difference between JavaScript objects and Map:
Object | Map |
---|---|
Cannot be directly iterated | Can be directly iterated |
No size property | Has size property |
Keys must be strings or Symbols | Keys can be any data type |
The order of keys is not clear | Keys are sorted by insertion order |
Default keys | No default keys |
Complete Map Reference Manual
For a complete reference, please visit our:JavaScript Map Reference Manual.
This manual includes descriptions and examples of all Map properties and methods.
Browser Support
Map is ES6 Features(JavaScript 2015).
Starting from June 2017, all modern browsers support ES6:
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 51 | Edge 15 | Firefox 54 | Safari 10 | Opera 38 |
May 2016 | April 2017 | June 2017 | September 2016 | June 2016 |
Internet Explorer does not support Map.
- Previous Page JS Set Methods
- Next Page JS Map Methods