A Map in JavaScript is a collection of key–value pairs, similar to an object, but with some powerful differences.
set(), get(), has(), delete(), clear(), forEach(), keys(), values(), and entries().? Great for dynamic key–value data
map.size gives the number of entries in the Map.Map over plain objects when keys are dynamic or you frequently add/remove entries.Use the new Map() constructor to create an empty Map or from an array of key–value pairs.
const myMap = new Map();
myMap.set("name", "John");
myMap.set("age", 30);
console.log(myMap);
const fruits = new Map([
["apple", 500],
["banana", 300],
["orange", 200]
]);
The set(key, value) method adds a new entry or updates an existing key with a new value.
fruits.set("grape", 150);
The get(key) method returns the value associated with a given key.
console.log(fruits.get("banana")); // Output: 300
The has(key) method returns true if the key exists in the Map, otherwise false.
console.log(fruits.has("apple")); // true
The delete(key) method removes the entry with the given key and returns true if successful.
fruits.delete("orange");
The clear() method removes all entries from the Map.
fruits.clear();
The forEach() method executes a callback for each key–value pair in the Map.
fruits.forEach((value, key) => {
console.log(key + " = " + value);
});
The keys() method returns an iterator over all keys in insertion order.
for (let key of fruits.keys()) {
console.log(key);
}
The values() method returns an iterator over all values.
for (let val of fruits.values()) {
console.log(val);
}
The entries() method returns an iterator with [key, value] pairs.
for (let entry of fruits.entries()) {
console.log(entry);
}
const fruits = new Map([
["apple", 500],
["banana", 300],
["orange", 200]
]);
fruits.set("grape", 150);
console.log("banana =", fruits.get("banana"));
console.log("has apple?", fruits.has("apple"));
fruits.delete("orange");
fruits.forEach((value, key) => {
console.log(key + " = " + value);
});
fruits Map with three entries."grape" with quantity 150."banana" using get()."apple" exists using has()."orange" entry with delete().forEach() to log all remaining key–value pairs.The final iteration prints something like:
apple = 500 banana = 300 grape = 150
This confirms that "orange" was removed and that the Map maintained the insertion order of keys.
map.set() and map.get() instead of object-style map.key access.map.clear() to empty a Map instead of reassigning it to {}.keys(), values(), and entries() with for...of loops for clean, readable iteration.Map of student names and their grades (e.g., "Alice" → 95).set() to add at least 4 students, then use get() to retrieve one student’s grade.keys()values()entries()has() to check if a particular student exists in the Map.delete() to remove one student and confirm removal with has().clear() to empty the Map and log map.size to verify.