JavaScript Map Data Structure
A Map in JavaScript is a collection of key-value pairs where keys can be of any type. Maps maintain the insertion order of their elements, unlike regular objects.
Common use cases:
- Associative data: Store relationships between keys and values.
- Efficient lookups: Quickly access values using keys.
- Preserve order: Retain the insertion order of items.
- Flexible keys: Use objects or functions as keys.
Quick Links
Map vs Object: What’s the Difference?
While both Map and Object can store key-value pairs, they are built for different use cases. Understanding the differences can help you decide which one to use.
🔍 Key Differences
- Key Types: Map allows any data type as a key (objects, functions, etc.), while Object keys are always strings or symbols.
- Order: Map maintains insertion order of keys. Object does not guarantee key order (except for string keys in modern JavaScript).
- Iteration: Map is directly iterable using for...of. For Object, you need to use Object.keys(), Object.entries(), etc.
- Performance: Map is generally faster for frequent additions/removals of key-value pairs.
- Utility: Map has a cleaner API with built-in methods like set(), get(), has(), and delete().
📊 Comparison Table
Feature | Map | Object |
---|---|---|
Key Types | Any (objects, functions, etc.) | Strings or Symbols |
Order | Maintained | Not guaranteed (except strings) |
Iterability | Directly iterable | Requires conversion |
Performance | Better for dynamic keys | Better for static key sets |
Use Case | Dynamic collections | Structured data (like models) |
In general, use Map when you need dynamic keys, insertion order, or efficient frequent updates. Use Object when working with fixed structures or JSON-style data.
Understanding the Map Data Structure
A Map in JavaScript is a collection of key-value pairs where the keys can be of any type—unlike regular objects, which only accept strings or symbols as keys.
Maps maintain the insertion order of their elements, which makes them especially useful when you need to preserve the sequence of entries.
// Creating a new Map
const userRoles = new Map();
// Adding key-value pairs
userRoles.set('Tom', 'admin');
userRoles.set('Jack', 'editor');
userRoles.set('John', 'viewer');
console.log(userRoles);
// Creating a new Map
const userRoles = new Map();
// Adding key-value pairs
userRoles.set('Tom', 'admin');
userRoles.set('Jack', 'editor');
userRoles.set('John', 'viewer');
console.log(userRoles);
- new Map(): Initializes a new empty map.
- .set(key, value): Adds a new entry to the map.
- Key types: Can be objects, functions, or any primitive type.
- Order: Keys retain insertion order when iterating.
The Map object is more flexible than regular objects when you need reliable key ordering or non-string keys.
Creating a Map
You can create a Map in JavaScript using the new Map() constructor. You can start with an empty map or initialize it with key-value pairs.
1. Creating an Empty Map
To create an empty map, use the new Map() constructor and add entries using the set() method.
// Creating an empty Map
const capitals = new Map();
// Adding key-value pairs
capitals.set('France', 'Paris');
capitals.set('Japan', 'Tokyo');
console.log(capitals);
// Output: Map(2) { 'France' => 'Paris', 'Japan' => 'Tokyo' }
// Creating an empty Map
const capitals = new Map();
// Adding key-value pairs
capitals.set('France', 'Paris');
capitals.set('Japan', 'Tokyo');
console.log(capitals);
// Output: Map(2) { 'France' => 'Paris', 'Japan' => 'Tokyo' }
2. Creating a Map with Initial Values
You can also initialize a map with an array of key-value pairs. Each pair should be an array with two elements: the key and the value.
// Creating a Map with initial values
const userRoles = new Map([
['Tom', 'admin'],
['Jack', 'editor'],
['John', 'viewer']
]);
console.log(userRoles.get('Tom')); // Output: admin
// Creating a Map with initial values
const userRoles = new Map([
['Tom', 'admin'],
['Jack', 'editor'],
['John', 'viewer']
]);
console.log(userRoles.get('Tom')); // Output: admin
This approach is concise and useful when you already have data to initialize your Map with.
Accessing Map Elements
Once you've added key-value pairs to a Map, you can retrieve values using their corresponding keys. JavaScript provides several methods to work with the contents of a map.
1. Using get()
The get(key) method returns the value associated with a specific key. If the key is not found, it returns undefined.
const userRoles = new Map([
['Tom', 'admin'],
['Jack', 'editor']
]);
console.log(userRoles.get('Tom')); // Output: admin
console.log(userRoles.get('John')); // Output: undefined
const userRoles = new Map([
['Tom', 'admin'],
['Jack', 'editor']
]);
console.log(userRoles.get('Tom')); // Output: admin
console.log(userRoles.get('John')); // Output: undefined
2. Using has() to Check Existence
Use the has(key) method to check if a map contains a specific key. It returns true or false.
console.log(userRoles.has('Tom')); // Output: true
console.log(userRoles.has('John')); // Output: false
console.log(userRoles.has('Tom')); // Output: true
console.log(userRoles.has('John')); // Output: false
3. Accessing All Keys, Values, or Entries
Maps provide methods to access all keys, values, or entries:
- map.keys() – returns an iterator for all keys
- map.values() – returns an iterator for all values
- map.entries() – returns an iterator for key-value pairs
const userRoles = new Map([
['Tom', 'admin'],
['Jack', 'editor']
]);
for (const key of userRoles.keys()) {
console.log(key);
}
// Output: Tom, Jack
for (const value of userRoles.values()) {
console.log(value);
}
// Output: admin, editor
for (const [key, value] of userRoles.entries()) {
console.log(key, '=>', value);
}
// Output: Tom => admin, Jack => editor
const userRoles = new Map([
['Tom', 'admin'],
['Jack', 'editor']
]);
for (const key of userRoles.keys()) {
console.log(key);
}
// Output: Tom, Jack
for (const value of userRoles.values()) {
console.log(value);
}
// Output: admin, editor
for (const [key, value] of userRoles.entries()) {
console.log(key, '=>', value);
}
// Output: Tom => admin, Jack => editor
These methods are useful for looping through all items in a Map, especially when you want to work with keys and values together.
Modifying Map Elements
JavaScript Map objects are mutable—you can add new key-value pairs, update existing ones, remove specific entries, or clear the entire map.
1. Adding New Entries
Use the set() method to add a new key-value pair to the map. If the key doesn't exist yet, it will be added; if it does, the value will be updated.
const inventory = new Map();
// Adding new key-value pairs
inventory.set('apples', 50);
inventory.set('bananas', 30);
console.log(inventory.get('apples')); // Output: 50
const inventory = new Map();
// Adding new key-value pairs
inventory.set('apples', 50);
inventory.set('bananas', 30);
console.log(inventory.get('apples')); // Output: 50
2. Updating an Existing Value
Calling set() with an existing key will update its value.
// Updating the value for an existing key
inventory.set('apples', 60);
console.log(inventory.get('apples')); // Output: 60
// Updating the value for an existing key
inventory.set('apples', 60);
console.log(inventory.get('apples')); // Output: 60
3. Deleting an Entry
Use delete(key) to remove a specific entry from the map. It returns true if the item was removed.
inventory.delete('bananas');
console.log(inventory.has('bananas')); // Output: false
inventory.delete('bananas');
console.log(inventory.has('bananas')); // Output: false
4. Clearing All Entries
Use the clear() method to remove all key-value pairs from the map.
inventory.clear();
console.log(inventory.size); // Output: 0
inventory.clear();
console.log(inventory.size); // Output: 0
These tools let you fully manage the contents of a Map, whether you're adding fresh data, updating it, or removing it when it's no longer needed.
Frequently Asked Questions
What is a Map in JavaScript?
What is a Map in JavaScript?
A Map is a key-value data structure that allows any type of key, including objects. It maintains the order of entries and provides helpful methods for managing and accessing those entries.
How do you create a Map in JavaScript?
How do you create a Map in JavaScript?
Create a Map with the new Map() constructor. You can also pass an array of key-value pairs: const map = new Map([[1, 'one'], [2, 'two']]).
How do you access values in a JavaScript Map?
How do you access values in a JavaScript Map?
Use the get() method with the key, like map.get('key'), to retrieve the value associated with it.
What are some useful Map methods?
What are some useful Map methods?
Common methods include set(), get(), has(), delete(), clear(), and iteration methods like keys(), values(), and entries().
How is Map different from Object in JavaScript?
How is Map different from Object in JavaScript?
Unlike Object, a Map can use any type as a key, maintains insertion order, and offers better performance for dynamic key-value operations.
What's Next?
Up next: JavaScript Map Methods. Maps store key-value pairs and provide useful methods like set
, get
, keys
, and values
to efficiently manage and access data.