JavaScript Map Methods
8 April 2025 | Category: JavaScript
The Map
object in JavaScript offers several methods to manage key-value pairs efficiently. These methods allow you to add, retrieve, delete, and iterate through items.
📌 1. set(key, value)
Adds a new element with the specified key and value to the Map. If the key already exists, the value will be updated.
✅ Syntax:
map.set(key, value);
🧪 Example:
const map = new Map();
map.set("name", "Alice");
map.set("age", 25);
console.log(map); // Map(2) { "name" => "Alice", "age" => 25 }
📌 2. get(key)
Returns the value associated with the given key.
✅ Syntax:
map.get(key);
🧪 Example:
console.log(map.get("name")); // Alice
📌 3. delete(key)
Removes the element associated with the specified key.
✅ Syntax:
map.delete(key);
🧪 Example:
map.delete("age");
console.log(map); // Map(1) { "name" => "Alice" }
📌 4. has(key)
Checks whether the Map contains a specific key. Returns true
or false
.
✅ Syntax:
map.has(key);
🧪 Example:
console.log(map.has("name")); // true
console.log(map.has("age")); // false
📌 5. clear()
Removes all key-value pairs from the Map.
✅ Syntax:
map.clear();
🧪 Example:
map.clear();
console.log(map); // Map(0) {}
📌 6. size
Returns the number of key-value pairs in the Map.
✅ Syntax:
map.size;
🧪 Example:
const fruits = new Map([
["apple", 10],
["banana", 20],
]);
console.log(fruits.size); // 2
📌 7. forEach(callback)
Calls the provided function once for each key-value pair in the Map.
✅ Syntax:
map.forEach(function(value, key, map) {
// your logic
});
🧪 Example:
fruits.forEach((value, key) => {
console.log(`${key} = ${value}`);
});
Output:
apple = 10
banana = 20
📌 8. [Symbol.iterator]()
or entries()
Returns an iterator of [key, value]
pairs, making it usable in a for...of
loop.
✅ Example:
for (let [key, value] of fruits) {
console.log(key, value);
}
📌 9. keys()
Returns an iterator with all the keys in the Map.
✅ Example:
for (let key of fruits.keys()) {
console.log(key);
}
📌 10. values()
Returns an iterator with all the values in the Map.
✅ Example:
for (let value of fruits.values()) {
console.log(value);
}
📌 11. entries()
Returns an iterator of [key, value]
pairs — same as using the default Map iterator.
✅ Example:
for (let entry of fruits.entries()) {
console.log(entry);
}
🧾 Summary Table
Method / Property | Description |
---|---|
set(key, value) | Adds or updates a key-value pair |
get(key) | Gets the value by key |
delete(key) | Removes the key-value pair |
has(key) | Checks if a key exists |
clear() | Clears all entries |
size | Returns total entries in Map |
forEach() | Iterates over each entry |
keys() | Returns an iterator of all keys |
values() | Returns an iterator of all values |
entries() | Returns an iterator of key-value pairs |
[Symbol.iterator]() | Same as entries() — enables for...of loop |