Map in Node.js
Complete guide to JavaScript Map: creation, CRUD operations, key existence checks, size, keys & values retrieval, traversal, merging maps and objects, and comparison with plain objects.
Map Basics
Map is a built-in JavaScript data structure for storing key-value pairs. It preserves insertion order and allows keys of any data type.
1. Creating an Empty Map
Use the Map constructor.
2. Setting a Key-Value Pair
Use set(key, value).
3. Checking if a Key Exists
Use has(key).
4. Accessing Value on a Specific Key
Use get(key).
5. Updating Value on a Specific Key
Call set() on an existing key.
6. Deleting a Key-Value Pair
Use delete(key).
7. Clearing the Map
Use clear().
8. Getting Map Size
Use the size property.
Map Keys & Values
Map provides iterators to access keys and values separately.
1. Getting Keys List of a Map
Use map.keys().
2. Getting Values List of a Map
Use map.values().
Traversing a Map
Maps and objects both support traversal, but through different APIs.
1. Traversing a Map using for...of
Iterate over [key, value] pairs.
2. Traversing a Map using forEach
Callback-based traversal.
3. Traversing an Object using Object.entries
Use for...of with Object.entries.
Merging Maps and Objects
Maps and objects can be merged using spread syntax.
1. Merging Two Maps
Use spread operator.
2. Merging Two Objects
Use object spread.