JavaScript Maps
A Map
stores key-value pairs and remembers the original insertion order of keys. Unlike objects, map keys can be of any type, and map sizes are easily obtained.
Key Topics
Creating Maps
Use the new Map()
constructor to create a map from an array of key-value pairs.
let myMap = new Map([
["key1", "value1"],
["key2", "value2"]
]);
console.log(myMap);
Output
> Map { "key1" => "value1", "key2" => "value2" }
Explanation: The map is initialized with two key-value pairs.
Map Operations
Methods like set()
, get()
, has()
, and delete()
manage map entries.
myMap.set("key3", "value3");
console.log(myMap.get("key1"));
console.log(myMap.has("key2"));
myMap.delete("key1");
console.log(myMap.size);
Output
> value1
> true
> 2
Explanation: "key3" is added, "key1" is deleted, and we confirm "key2" exists. The size after modifications is 2.
Iterating Maps
Use for...of
or forEach()
to iterate over maps. entries()
, keys()
, and values()
return iterators.
JavaScript Usage in DOM
Maps can store configuration or data keyed by objects or strings, which can be displayed or manipulated on webpages.
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Maps in DOM</title></head>
<body>
<h1>Map Demo</h1>
<button onclick="showMap()">Show Map</button>
<p id="display"></p>
<script>
function showMap() {
let info = new Map();
info.set("Name", "Alice");
info.set("Role", "Developer");
let result = "";
for (let [key, value] of info) {
result += key + ": " + value + " ";
}
document.getElementById("display").textContent = result;
}
</script>
</body>
</html>
Key Takeaways
- Maps: Store key-value pairs with keys of any type.
- Methods:
set()
,get()
,has()
,delete()
manage entries. - Iteration:
for...of
and iterators make it easy to traverse maps. - DOM Integration: Manage dynamic data keyed by various identifiers for display.