Understanding JavaScript's Map data structure
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:
We can optionally initialize it with an array of arrays, each representing a key-value pair:
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.
We can also use objects or functions as keys in a Map:
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.
Checking if an element exists in a Map
We can check if a key is present in a Map using the has(key)
method.
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.
Counting the number of elements in the Map
We can get the number of elements stored in the Map using the size
property.
Removing all elements from the Map
The clear()
method efficiently empties the entire Map: