JavaScript Map
Map is a set of key-value pairs, where keys are unique.
Creat a Map
Map() constructor can be used to create a Map in JavaScript.
</>
Copy
var map1 = new Map();
Insert Key-Value Pair
Map.set() method inserts a new key-value pair, or update the value if the key is already present.
</>
Copy
map1.set(key, value);
Get Value for a Specific Key
Map.get() method returns the value of specified key from this Map.
</>
Copy
var value = map1.get(key);
Delete a Specific Key
Map.delete() method deletes the specified key from this Map.
</>
Copy
var isDeleted = map1.delete(key);
If Map has a Specific Key
Map.has() method checks if this Map has specified key.
</>
Copy
var isKeyPresentInMap = map1.has(key);
Execute a Function for Each Key-Value Pair
Map.forEach() method executes a specified function for each key-value pair of this Map.
</>
Copy
map1.forEach (function(value, key) {
//code
})
JavaScript Map Tutorials
The following tutorials cover concepts on a JavaScript Map in detail with examples.
- JavaScript – Create a Map
- JavaScript – Insert a Key-Value to Map
- JavaScript – Get Map Size
- JavaScript – Get Value for Specific Key in Map
- JavaScript – Delete a Specific Key from Map
- JavaScript – Check if Map has Specific Key
- JavaScript – Iterate over Key-Value pairs of Map
- JavaScript – Map forEach()
Conclusion
In this JavaScript Tutorial, we learned about Maps in JavaScript.