JavaScript Maps


A map is a collection of key-value pairs, where the keys can be of any data type.

A map keeps track of the order in which keys were first added.

A map has a characteristic that shows how big the map is.

Map Methods

MethodDescription
new Map()Generates a fresh Map object.
set()Assigns a value to a specific key in a Map.
get()Retrieves the value associated with a specific key in a Map.
clear()Deletes all items from a Map.
delete()Deletes a Map item identified by a specific key.
has()Determines whether a specific key is present in a Map.
forEach()Triggers a function for every key/value combination in a Map.
entries()Produces a tool that iterates through the [key, value] pairs within a Map.
keys()Produces an iterator that contains the keys of a Map.
values()Produces a sequence of values from a Map.
PropertyDescription
sizeReturns the count of Map elements.

How to Create a Map

You can make a JavaScript Map by:

  • Using an array with new Map().
  • Build a map and employ the Map.set() method.

new Map()

To make a map, you can use an array with the new Map() constructor.


Map.set()

You can put things into a Map by using the set() method.

You can use the set() method to modify values in an existing Map.


Map.get()

The get() method is used to retrieve the value associated with a specific key in a Map.


Map.size

The size property tells you how many elements are in a Map.


Map.delete()

The delete() method is used to get rid of a Map element.


Map.clear()

The clear() method eliminates all elements from a Map.


Map.has()

The has() function tells you if a specific key is present in a Map.


Maps are Objects

typeof tells us that the result is an object.

instanceof Map will give a result of true.


JavaScript Objects vs Maps

Differences between JavaScript Objects and Maps:

ObjectMap
Not easily looped through. Directly iterable
The size property is absent. Include a "size" attribute.
Key values need to be either Strings or Symbols. Keys can have various types of data.
The keys are not properly arranged. Keys are arranged based on when they are added.
Use the default keys. Avoid using preset keys.

Map.forEach()

The forEach() method calls a function for every key/value pair in a Map.


Map.entries()

The entries() method gives back an iterator object containing [key, values] pairs from a Map.


Map.keys()

The keys() method gives back a list of keys from a Map in the form of an iterator object.


Map.values()

The values() method gives back an iterator object containing the values within a Map.

You can employ the values() method to add up the values in a Map.


Objects as Keys

Using objects as keys is a crucial feature in Map functionality.

Note: The important thing is an aboject (apples), not just a string ("apples").