Clean β’ Professional
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.
.size returns the number of entries.for...of, forEach, or spread operators.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']
]);
| 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 |
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);
});Β