Js Maps in JavaScript
?? JavaScript Maps
A Map in JavaScript is a collection of key-value pairs where:
Keys can be any data type (objects, functions, primitives)
Keys maintain the insertion order
Maps are iterable
Why use a Map instead of a plain object?
Objects only allow strings and symbols as keys
Maps allow any type as a key (e.g., objects, functions)
Maps have a
sizeproperty (easy to get the number of entries)Maps are designed specifically for mapping key-value pairs with useful built-in methods
Creating a Map
const map = new Map();Or initialize with an array of key-value pairs:
const map = new Map([ ['name', 'Alice'], ['age', 25]]);Basic Operations
const map = new Map();// Add entriesmap.set('name', 'Bob');map.set(42, 'The answer');map.set(true, 'Yes');// Get valuesconsole.log(map.get('name')); // Bobconsole.log(map.get(42)); // The answer// Check if key existsconsole.log(map.has(true)); // true// Size of mapconsole.log(map.size); // 3// Delete an entrymap.delete(42);// Clear all entries// map.clear();Iterating over a Map
for (const [key, value] of map) { console.log(`${key} => ${value}`);}Map vs Object
| Feature | Map | Object |
|---|---|---|
| Key types | Any type | Strings and Symbols only |
| Order | Maintains insertion order | Not guaranteed |
| Size property | Yes (map.size) | No (need to compute) |
| Iteration | Directly iterable | Use Object.keys() etc. |
| Performance | Optimized for frequent add/remove | Not optimized for map-like use |
Want a practical example using Maps, or help converting Maps to arrays/objects?