JavaScript Maps
JavaScript Maps
A Map is a collection of key-value pairs in JavaScript. Unlike objects, Maps allow:
โ Any type of key (objects, functions, numbers, strings)
โ Values to be stored in insertion order
โ Easy size checking
๐งฉ Creating a Map
โ Adding Key-Value Pairs
Use the .set() method:
๐ Getting Values
โ Checking Keys
๐ Removing Items
๐งน Clear All Items
๐ Size of a Map
๐ Iterating Through a Map
Loop through keys and values:
Using forEach():
๐ Useful Methods Summary
| Method | Description |
|---|---|
set(key, value) |
Adds or updates entry |
get(key) |
Returns value for the key |
has(key) |
Checks if key exists |
delete(key) |
Removes key/value |
clear() |
Removes all entries |
size |
Number of items |
๐ Map vs Object
| Feature | Map | Object |
|---|---|---|
| Key type | Any type | String/symbol only |
| Ordered | Yes | No guarantee |
| Iterable | Yes | No (needs conversion) |
| Size tracking | size property |
Must count manually |
โญ Practical Example: Counting Occurrences
Output:
