JavaScript Maps Overview
A Map in JavaScript is a collection of key-value pairs where keys can be of any data type, unlike objects where keys are typically strings or symbols. Maps maintain insertion order, making them suitable for storing structured data with flexible key types.
- Any Key Type: Keys can be objects, functions, numbers, or strings.
- Ordered: Keys are iterated in the order of insertion.
- Size Property:
.size
returns the number of entries. - Iterable: Maps can be looped using
for...of
,forEach
, or spread operators. - Better Performance: For frequent additions and removals, Maps are often more efficient than plain objects.
Creating Maps
a. Using Map Constructor
const map = new Map();
map.set('name', 'Alice');
map.set(1, 'Number Key');
map.set(true, 'Boolean Key');
b. Using an Array of Key-Value Pairs
const map = new Map([
['name', 'Alice'],
[1, 'Number Key'],
[true, 'Boolean Key']
]);
Map Methods
Method | Description |
---|---|
.set(key, value) | Adds or updates a key-value pair |
.get(key) | Returns the value associated with the key |
.has(key) | Checks if the key exists (returns boolean) |
.delete(key) | Removes the key-value pair |
.clear() | Removes all entries from the Map |
.size | Returns the number of entries |
.keys() | Returns an iterator of keys |
.values() | Returns an iterator of values |
.entries() | Returns an iterator of [key, value] pairs |
.forEach(callback) | Executes a function for each key-value pair |
Iterating Over a Map
a. Using for...of
for (const [key, value] of map) {
console.log(key, value);
}
b. Using .forEach()
map.forEach((value, key) => {
console.log(key, value);
});