Overview of Maps in JavaScript

A Map is a built-in JavaScript object that holds key-value pairs, maintaining the order of insertion. Unlike objects, keys in maps can be any data type including functions, objects, and primitives.

const map = new Map();

Creating and Initializing a Map

Using the Constructor

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2']
]);

This creates a new map with two entries.

Common Methods

map.set('a', 1);
console.log(map.get('a'));  // 1
console.log(map.has('a'));  // true
map.delete('a');

Iterating Through a Map

Methods for Iteration

for (let [key, value] of map) {
  console.log(key, value);
}

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

Comparison: Map vs Object

Feature Map Object
Key types Any (including objects) Strings & Symbols only
Order Preserved Not guaranteed
Performance Better for frequent additions/removals Better for static structure

Use Cases