A Map
is a built-in JavaScript object that holds key-value pairs, maintaining the order of insertion. Unlike objects, keys in maps can be any data type including functions, objects, and primitives.
const map = new Map();
const map = new Map([
['key1', 'value1'],
['key2', 'value2']
]);
This creates a new map with two entries.
set(key, value)
– Adds or updates an entry.get(key)
– Retrieves the value by key.has(key)
– Returns true
if the key exists.delete(key)
– Removes the key and value.clear()
– Removes all entries.size
– Returns the number of entries.map.set('a', 1);
console.log(map.get('a')); // 1
console.log(map.has('a')); // true
map.delete('a');
map.keys()
– Returns an iterator over keys.map.values()
– Iterator over values.map.entries()
– Iterator over key-value pairs.map.forEach(callback)
– Executes callback for each entry.for (let [key, value] of map) {
console.log(key, value);
}
map.forEach((value, key) => {
console.log(`${key} => ${value}`);
});
Feature | Map | Object |
---|---|---|
Key types | Any (including objects) | Strings & Symbols only |
Order | Preserved | Not guaranteed |
Performance | Better for frequent additions/removals | Better for static structure |
forEach
without side-effects from prototypes