askvity

What is a Map in JS?

Published in JavaScript Data Structure 3 mins read

A Map in JavaScript is a built-in object that stores collections of key-value pairs. It's a fundamental data structure used for associating data points together.

Understanding JavaScript Maps

Think of a Map as a dictionary or a lookup table where each item has both a unique key and a corresponding value. The key is used to find or retrieve the value.

Based on the definition, Map objects are collections of key-value pairs.

Key Characteristics of a JavaScript Map

Maps have several important features that define how they work:

  • Key-Value Storage: Like an object, a Map stores data in key: value pairs.
  • Unique Keys: A key in the Map may only occur once; it is unique within the Map's collection. If you try to add a new entry with an existing key, it will overwrite the previous value associated with that key.
  • Ordered Insertion: Maps remember the original order of insertion of keys. This can be useful for iteration.
  • Flexible Keys: Unlike plain JavaScript objects where keys are often restricted to strings or Symbols, Map keys can be any data type, including objects, functions, or primitive values.
  • Iteration: A Map object is iterated by key-value pairs. Using a for...of loop on a Map returns a 2-member array of [key, value] for each iteration, allowing you to easily access both parts of the pair.

Here's a quick summary of core features derived from its definition:

Feature Description
Storage Collection of key-value pairs
Key Uniqueness Each key is unique; appears only once
Iteration for...of yields [key, value] arrays

Basic Usage Example

Creating and using a Map is straightforward:

// Create a new Map
const myMap = new Map();

// Add key-value pairs
myMap.set('name', 'Alice');
myMap.set(1, 'a number key');
const myObject = { id: 1 };
myMap.set(myObject, 'an object key');

console.log(myMap.get('name')); // Output: Alice
console.log(myMap.get(1));    // Output: a number key
console.log(myMap.get(myObject)); // Output: an object key

// Check if a key exists
console.log(myMap.has('name')); // Output: true

// Iterate over the Map
console.log("Map contents:");
for (const [key, value] of myMap) {
  console.log(`${typeof key}: ${key} => ${value}`);
}
// Output:
// string: name => Alice
// number: 1 => a number key
// object: { id: 1 } => an object key

// Get the size
console.log(`Map size: ${myMap.size}`); // Output: 3

// Delete a pair
myMap.delete('name');
console.log(myMap.has('name')); // Output: false
console.log(`New map size: ${myMap.size}`); // Output: 2

Maps are particularly useful when you need a collection where keys are not limited to strings/Symbols, the order of items matters, or you need efficient addition/deletion of key-value pairs.

Related Articles