JavaScript Map


In JavaScript, a Map is a powerful data structure that stores key-value pairs. Unlike objects, which can only have strings or symbols as keys, Maps can have keys of any type, including objects, functions, and primitive values. The Map object also provides useful methods for iterating over its contents, checking its size, and getting, setting, and deleting items.


1. What is a JavaScript Map?

A Map is a collection of key-value pairs where both the key and the value can be any data type, unlike objects, which only allow strings and symbols as keys.

Syntax to Create a Map

You can create a Map using the new Map() constructor:

const myMap = new Map();

This creates an empty map. You can also initialize a map with key-value pairs when creating it:

const myMap = new Map([
  ['name', 'John'],
  ['age', 30],
  ['city', 'New York']
]);

Here, ['name', 'John'], ['age', 30], and ['city', 'New York'] are key-value pairs, where the first element is the key and the second is the value.


2. Key Features of a Map

  • Key-Value Pairs: A Map stores pairs of keys and values, similar to objects.
  • Ordered Entries: Maps remember the order of the elements. When you iterate over a Map, the key-value pairs are returned in the order they were added.
  • Any Data Type as a Key: Unlike objects, which only accept strings and symbols as keys, Maps can use any data type, such as objects, functions, or primitive values.
  • Map Size: The size property of a Map tells you the number of key-value pairs it contains.

3. Basic Operations with Maps

3.1 Adding Items to a Map

To add a new key-value pair to a Map, you can use the set() method.

const myMap = new Map();
myMap.set('name', 'Alice');
myMap.set('age', 25);
myMap.set('city', 'Los Angeles');

In this example, we use the set() method to add three key-value pairs to the Map.

3.2 Accessing Values in a Map

To retrieve the value associated with a key, you can use the get() method.

const name = myMap.get('name');
console.log(name);  // Output: Alice

3.3 Checking if a Key Exists

To check if a key exists in a Map, use the has() method.

const hasCity = myMap.has('city');
console.log(hasCity);  // Output: true

3.4 Removing Items from a Map

To remove a key-value pair from a Map, use the delete() method.

myMap.delete('age');
console.log(myMap.has('age'));  // Output: false

3.5 Clearing a Map

To remove all the key-value pairs from a Map, use the clear() method.

myMap.clear();
console.log(myMap.size);  // Output: 0

4. Iterating Over Maps

Maps provide several ways to iterate over the key-value pairs:

4.1 Using forEach()

The forEach() method allows you to iterate over the Map and execute a function on each key-value pair.

myMap.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

4.2 Using for...of Loop

You can also use a for...of loop to iterate over the entries of the Map. The entries() method returns an iterator for the key-value pairs.

for (let [key, value] of myMap) {
  console.log(`${key}: ${value}`);
}

This will output each key-value pair in the Map.

4.3 Iterating Over Keys and Values Separately

If you want to iterate over only the keys or values of a Map, you can use the keys() and values() methods, respectively.

// Iterate over the keys
for (let key of myMap.keys()) {
  console.log(key);
}

// Iterate over the values
for (let value of myMap.values()) {
  console.log(value);
}

5. Map Methods

Maps come with several useful methods that help with different operations:

  • set(key, value): Adds a new key-value pair or updates an existing one.
  • get(key): Retrieves the value associated with the key.
  • has(key): Checks if a key exists in the Map.
  • delete(key): Removes a key-value pair.
  • clear(): Clears all key-value pairs.
  • size: Returns the number of key-value pairs.
  • keys(): Returns an iterator for the keys in the Map.
  • values(): Returns an iterator for the values in the Map.
  • entries(): Returns an iterator for the key-value pairs.
  • forEach(callback): Executes a callback for each key-value pair.

6. Comparing Maps and Objects

While both Maps and Objects store key-value pairs, there are key differences between the two:

Feature Map Object
Key Type Any type (primitive, object, function) Only strings and symbols as keys
Iteration Order Maintains insertion order Does not guarantee insertion order
Size Property Has a size property Does not have a size property
Performance (for large data) Optimized for frequent additions/removals Slower for large sets of data
Methods .set(), .get(), .has(), .delete() Access via bracket or dot notation

7. Use Cases for JavaScript Map

The Map object is often used in scenarios where you need to:

  • Store a collection of data with complex keys (e.g., objects or arrays as keys).
  • Preserve the insertion order of keys and values.
  • Perform frequent additions, deletions, or lookups.
  • Improve performance when working with a large number of key-value pairs.

Here are some real-world use cases for Map:

  • Caching Results: Maps can be used to store pre-computed values for faster lookup.
  • Mapping User Preferences: You can use a Map to store user settings, preferences, or configurations where the keys are the option names and the values are the settings.