JavaScript Maps


A map is like a dictionary. It pairs keys with values. Keys can be any type of data.

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

Essential Map Methods

MethodDescription
new Map()Creates a new Map
set()Sets the value for a key in a Map
get()Gets the value for a key in a Map
delete()Removes a Map element specified by the key
has()Returns true if a key exists in a Map
forEach()Calls a function for each key/value pair in a Map
entries()Returns an iterator with the [key, value] pairs in a Map
PropertyDescription
sizeReturns the number of elements in a Map

How to Create a Map

You can create a JavaScript Map by:

  • Passing an Array to new Map()
  • Create a Map and use Map.set()

The new Map() Method

You can make a map by giving an array to the new Map() constructor.


The set() Method

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

You can update values in a Map by using the set() method.


The get() Method

The get() method gets the value of a key in a Map:


The size Property

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


The delete() Method

To remove an element from a Map, you can use the delete() method.


The has() Method

The has() function tells you whether a key is present in a Map, returning true if it is.


JavaScript Objects vs Maps

Differences between JavaScript Objects and Maps:

ObjectMap
Iterable Not directly iterable Directly iterable
Size Do not have a size property Have a size property
Key Types Keys must be Strings (or Symbols) Keys can be any datatype
Key Order Keys are not well ordered Keys are ordered by insertion
Defaults Have default keys Do not have default keys

The forEach() Method

You can use the forEach() method to execute a function for every key/value pair in a Map.


The entries() Method

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