A Map is a collection of key-value pairs where the keys can be of any data type. Unlike objects, where keys are usually strings or symbols, a Map key can even be an object or a function.
Maps provide a cleaner and more efficient API for managing key-value data compared to regular objects.
| Method | Description |
|---|---|
new Map() |
Creates a new Map |
set() |
Sets the value for a key in a Map |
get() |
Returns the value for a key |
has() |
Returns true if a key exists |
delete() |
Removes a Map element |
clear() |
Removes all the elements from a Map |
You can create a Map by passing an array to the new Map() constructor, or add
items using the set() method.
// Method 1: Creating with an array
const fruits = new Map([
["apples", 500],
["bananas", 300]
]);
// Method 2: Using set()
fruits.set("oranges", 200);
fruits.set("apples", 600); // Changes the existing value
The get() method retrieves a value, and has() checks for
existence.
console.log(fruits.get("bananas")); // 300
console.log(fruits.has("grapes")); // false
The most powerful feature of Maps is that they can use objects as keys. This is something
standard objects {} cannot do properly.
const user = { name: "Mim" };
const visits = new Map();
visits.set(user, 5); // Using an object as a key
console.log(visits.get(user)); // 5
| Feature | Object | Map |
|---|---|---|
| Key Types | String or Symbol | Any value (including Objects) |
| Size | Manual check required | Built-in size property |
| Order | Not strictly guaranteed | Maintains insertion order |
| Performance | Better for simple data | Better for large collections |
set() to add or update and
get() to readsize property gives the count of elements
immediately