Understanding JavaScript's Map data structure

Srijan } Author Pic
SrijanJan 27, 2025 - JavaScript
Understanding JavaScript's Map data structure - Reacted Node

Photo: Andrew Neel/Pexels

Introduction

The Map is a new JavaScript data structure introduced in the ES2015 or ES6 specification for managing key-value pairs. Unlike regular objects, where keys are typically strings or symbols, a Map allows us to use any datatype (including objects, arrays, and even other Maps) as keys.

While it might seem similar to regular objects at first glance, Map offers unique advantages and a more comprehensive range of capabilities that make it a valuable addition to JavaScript.

Table of Contents

Using Map

Map provides a comprehensive set of methods and properties for basic operations. Let's have a look at some of the core operations with Map in detail:

Creating a Map

To create an empty Map, we use the new Map() constructor:

1let myMap = new Map();

We can optionally initialize it with an array of arrays, each representing a key-value pair:

1// Map with Initial Values
2const studentScores = new Map([
3 ["Alice", 95],
4 ["Bob", 88],
5 ["Charlie", 76],
6]);

Adding a new Element to the Map

We can add a new Element to the Map using the set(key, value) method. If the key already exists in the Map, its associated value is updated.

1// We will use studentScores Map that we created earlier
2studentScores.set("David", 92); // Add David's score
3
4studentScores.set("Bob", 90); // Updates Bob score from 88 to 90

We can also use objects or functions as keys in a Map:

1const studentDetail = { name: "Nikhil" };
2studentScores.set(studentDetail, 95);
3console.log(studentScores);

Accessing an Element in a Map

Using the get(key) method, we can retrieve the value associated with a key. If the key is not found, undefined will be returned.

1console.log(studentScores.get("Bob")); // Output: 90

Checking if an element exists in a Map

We can check if a key is present in a Map using the has(key) method.

1console.log(studentScores.has("Alice")); // Output: true

Removing an element from the Map

We can delete an element from Map using delete(key) method. This method returns true if the key was found and removed or false if it wasn't present.

1studentScores.delete("Charlie");
2console.log(studentScores.has("Charlie")); // Output: false

Counting the number of elements in the Map

We can get the number of elements stored in the Map using the size property.

1console.log(studentScores.size); // Output: 2 (after deleting Charlie)

Removing all elements from the Map

The clear() method efficiently empties the entire Map:

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