JavaScript Create a Map
To create a Map in JavaScript, use Map() constructor. Map() constructor accepts an array of arrays, where inner array contains key and value as elements.
Syntax
The syntax to create a Map using Map() constructor is
new Map() //empty map new Map([[key, value], [key, value]]) //map from array
Examples
In the following example, we create an empty map, and insert some key-value pairs into it.
index.html
<!DOCTYPE html> <html lang="en"> <body> <pre id="output"></pre> <script> var map1 = new Map(); map1.set('a', 10); map1.set('b', 20); var displayOutput = ''; map1.forEach (function(value, key) { displayOutput += key + ' - ' + value + '\n'; }); document.getElementById('output').innerHTML += displayOutput; </script> </body> </html>
In the following example, we create a map with key-value pairs derived from an array of arrays passed as argument to Map() constructor.
index.html
<!DOCTYPE html> <html lang="en"> <body> <pre id="output"></pre> <script> var map1 = new Map([ ['a', 10], ['b', 20], ['c', 30] ]); var displayOutput = ''; map1.forEach (function(value, key) { displayOutput += key + ' - ' + value + '\n'; }); document.getElementById('output').innerHTML += displayOutput; </script> </body> </html>
Conclusion
In this JavaScript Tutorial, we learned how to create a Map in JavaScript using Map() constructor, with examples.