Map

A Map is a built-in JavaScript data structure that stores data as key-value pairs. Unlike plain objects, a Map allows any type as a key - strings, numbers, booleans, objects, or even arrays.

In a regular object, keys are always converted to strings (or symbols). A Map preserves the original type of the key, which makes it more flexible and predictable for certain use cases.

javascript

const map = new Map();

map.set("name", "Alice");   // string key
map.set(1, "one");          // number key
map.set(true, "yes");       // boolean key

console.log(map.get("name")); // Alice
console.log(map.get(1));      // one
console.log(map.get(true));   // yes

You create a Map using the new Map() constructor. You can create an empty Map and add entries later, or pass an array of [key, value] pairs directly to the constructor.

javascript

// Empty Map
const emptyMap = new Map();

// Map with initial values
const map = new Map([
  ["name", "Alice"],
  ["age", 25],
  ["city", "Paris"]
]);

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

Use map.set(key, value) to add or update a key-value pair. If the key already exists, the value is updated. If the key is new, a new entry is created.

javascript

const map = new Map();

map.set("language", "JavaScript");
map.set("version", 2024);

// Update existing key
map.set("language", "TypeScript");

console.log(map.get("language")); // TypeScript
console.log(map.get("version"));  // 2024

The set() method returns the Map itself, so you can chain multiple set() calls in a single statement. This is a clean way to add several entries at once.

javascript

const map = new Map();

map
  .set("name", "Bob")
  .set("age", 30)
  .set("city", "London");

console.log(map.size); // 3

JavaScript Map comes with a set of built-in methods and one property that make it easy to work with key-value data. Here is a quick overview:

  • set(key, value) - Add or update a key-value pair.
  • get(key) - Retrieve the value for a given key.
  • has(key) - Check whether a key exists in the Map.
  • size - Returns the number of entries in the Map.
  • clear() - Remove all entries from the Map.
  • delete(key) - Remove a specific entry by key.
  • keys() - Returns an iterator of all keys.
  • values() - Returns an iterator of all values.
  • entries() - Returns an iterator of all [key, value] pairs.
  • forEach(callback) - Runs a function for each entry in the Map.

Use map.get(key) to retrieve the value associated with a key. If the key does not exist, it returns undefined.

javascript

const map = new Map([
  ["fruit", "mango"],
  ["color", "yellow"]
]);

console.log(map.get("fruit"));   // mango
console.log(map.get("color"));   // yellow
console.log(map.get("taste"));   // undefined (key not found)

Use map.has(key) to check whether a key exists in the Map. It returns true if the key is present, and false if not.

javascript

const map = new Map([["name", "Alice"]]);

console.log(map.has("name"));  // true
console.log(map.has("email")); // false

The size property returns the number of key-value pairs stored in the Map. Unlike arrays, you do not use .length - Maps use .size.

javascript

const map = new Map();
map.set("a", 1);
map.set("b", 2);
map.set("c", 3);

console.log(map.size); // 3

The clear() method removes all key-value pairs from the Map, leaving it empty. The Map still exists after calling clear() - it just has no entries.

javascript

const map = new Map([["x", 10], ["y", 20]]);
console.log(map.size); // 2

map.clear();
console.log(map.size); // 0

Use map.delete(key) to remove a specific entry. It returns true if the key was found and removed, or false if the key did not exist.

javascript

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

map.delete("age");

console.log(map.has("age")); // false
console.log(map.size);       // 1

Because a Map can use any value as a key, you can use an array (or any object) as a key. Keep in mind that key lookup uses reference equality - the same array variable must be used to retrieve the value.

javascript

const coords = [10, 20];
const map = new Map();

map.set(coords, "location A");

console.log(map.get(coords));   // location A
console.log(map.get([10, 20])); // undefined (different array reference)

Two separate arrays with the same contents are not the same reference, so map.get([10, 20]) returns undefined even though the values look identical.

You can iterate over a Map using a for...of loop with map.entries(), map.keys(), or map.values(). Map entries are iterated in insertion order.

javascript

const map = new Map([["a", 1], ["b", 2], ["c", 3]]);

// Iterate over entries (key-value pairs)
for (const [key, value] of map.entries()) {
  console.log(key, value); // a 1, b 2, c 3
}

// Iterate over keys only
for (const key of map.keys()) {
  console.log(key); // a, b, c
}

// Iterate over values only
for (const value of map.values()) {
  console.log(value); // 1, 2, 3
}

You can convert a plain object to a Map using Object.entries(obj), which returns an array of [key, value] pairs that you can pass directly to new Map().

javascript

const person = { name: "Alice", age: 25, city: "Paris" };

const map = new Map(Object.entries(person));

console.log(map.get("name")); // Alice
console.log(map.size);        // 3

You can convert a Map to an array using the spread operator [...map] or Array.from(map). Both produce an array of [key, value] pairs.

javascript

const map = new Map([["a", 1], ["b", 2]]);

// Using spread operator
const arr1 = [...map];
console.log(arr1); // [['a', 1], ['b', 2]]

// Using Array.from
const arr2 = Array.from(map);
console.log(arr2); // [['a', 1], ['b', 2]]

// Keys or values only as arrays
const keys = [...map.keys()];     // ['a', 'b']
const values = [...map.values()]; // [1, 2]

The forEach method iterates over each entry in the Map and calls a callback function with (value, key, map) as arguments. Note that value comes before key - the opposite of what you might expect.

javascript

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

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

A WeakMap is similar to a Map but with two key differences: keys must be objects (not primitives), and the keys are held weakly. If there are no other references to the key object, it can be garbage collected automatically.

WeakMap does not support iteration, size, keys(), values(), or clear(). It is mainly used for storing private data tied to objects without preventing their garbage collection.

javascript

const weakMap = new WeakMap();

let user = { name: "Alice" };
weakMap.set(user, "admin");

console.log(weakMap.get(user)); // admin
console.log(weakMap.has(user)); // true

// When 'user' is set to null, the entry can be garbage collected
user = null;
  • Map - stores key-value pairs where keys can be of any type.
  • new Map() - creates a new Map, optionally initialized with [key, value] pairs.
  • set(key, value) - adds or updates an entry; returns the Map (chainable).
  • get(key) - retrieves the value for a key; returns undefined if not found.
  • has(key) - returns true if the key exists, otherwise false.
  • size - returns the number of entries in the Map.
  • clear() - removes all entries from the Map.
  • delete(key) - removes a specific entry by key.
  • Iteration - use for...of with entries(), keys(), or values().
  • Object to Map - use new Map(Object.entries(obj)).
  • Map to Array - use [...map] or Array.from(map).
  • forEach - callback receives (value, key) - value comes first.
  • WeakMap - like Map but keys must be objects and are weakly held (garbage collectible).