Maps
JavaScript recently added support for Maps: dedicated collections designed strictly for storing key-value pairs.
Unlike traditional Objects, Map keys are strictly unique, and Map instances are iterable by default.
Creating and Modifying Maps
You interact with a Map using its built-in .set(), .get(), and .delete() methods. Adding a key that already exists will simply overwrite its previous value.
// Initialize a new Map
const map = new Map();
// Add key-value pairs
map.set("Alice", "Admin");
map.set("Bob", "User");
map.set("Charlie", "User");
// Overwrite an existing key
map.set("Alice", "SuperAdmin");
console.log(map.get("Alice"));
// Output: "SuperAdmin"
// Delete a key
map.delete("Charlie");
Initializing from Iterables
The Map constructor can accept any iterable object (like an array of arrays) to quickly pre-populate the collection. Because Maps themselves are iterable, you can even pass an existing Map into the constructor to create a quick, shallow clone!
const originalMap = new Map();
originalMap.set("Alice", "Admin");
// Clones the map
const mapCopy = new Map(originalMap);
console.log(mapCopy.get("Alice")); // Output: "Admin"