Map in JavaScript

What is a Map in JavaScript?

A Map is a built-in data structure in JavaScript that allows you to store key-value pairs. It is similar to an object, but with a few important differences:

  • Order of elements: A Map maintains the insertion order of its keys, meaning you can iterate over a Map in the same order you inserted the key-value pairs.

  • Key types: In a Map, the keys can be of any data type (not just strings and symbols, like in regular objects). You can use objects, arrays, or primitive values as keys.


Creating a Map

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

const map1 = new Map();

Alternatively, you can initialize a Map with key-value pairs by passing an array of arrays:

const map2 = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

Basic Operations on Map

1. Set Method

The set() method is used to add a key-value pair to the Map.

const map = new Map();

map.set('name', 'Alice');
map.set('age', 25);

console.log(map);
// Map(2) { 'name' => 'Alice', 'age' => 25 }

2. Get Method

The get() method is used to retrieve the value associated with a specific key.

const map = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

console.log(map.get('name')); // Output: Alice
console.log(map.get('age')); // Output: 25

3. Has Method

The has() method checks if a specific key exists in the Map.

const map = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

console.log(map.has('name')); // Output: true
console.log(map.has('address')); // Output: false

4. Delete Method

The delete() method removes a specific key-value pair from the Map.

const map = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

map.delete('age');
console.log(map);
// Map(1) { 'name' => 'Alice' }

5. Clear Method

The clear() method removes all key-value pairs from the Map.

const map = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

map.clear();
console.log(map);
// Map(0) {}

6. Size Property

The size property returns the number of key-value pairs in the Map.

const map = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

console.log(map.size); // Output: 2

Iterating Over a Map

You can iterate over a Map using several methods:

1. forEach Method

The forEach() method allows you to execute a function for each key-value pair in the Map.

const map = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

map.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});
// Output:
// name: Alice
// age: 25

2. for...of Loop

You can also use the for...of loop to iterate over the Map:

const map = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

for (const [key, value] of map) {
  console.log(`${key}: ${value}`);
}
// Output:
// name: Alice
// age: 25

3. Keys, Values, and Entries

  • map.keys(): Returns an iterator for the keys.

  • map.values(): Returns an iterator for the values.

  • map.entries(): Returns an iterator for the key-value pairs.

const map = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

// Keys
for (const key of map.keys()) {
  console.log(key);
}
// Output:
// name
// age

// Values
for (const value of map.values()) {
  console.log(value);
}
// Output:
// Alice
// 25

// Entries (key-value pairs)
for (const [key, value] of map.entries()) {
  console.log(`${key}: ${value}`);
}
// Output:
// name: Alice
// age: 25

Comparison: Map vs. Object

FeatureMapObject
Key TypesAny data type (objects, arrays, etc.)Only strings and symbols
OrderMaintains insertion orderNo guaranteed order
IterationBuilt-in methods (forEach, keys, etc.)Uses for...in or Object.keys()
PerformanceGenerally faster for frequent additions/removalsSlower for frequent additions/removals

When to Use a Map

  • Use a Map when you need to store key-value pairs where keys are not limited to strings.

  • Use it when maintaining the insertion order of keys is important.

  • If you need methods like forEach(), keys(), values(), or entries() to easily iterate over the Map.