Map

A Map is an object in JavaScript that stores entries of key-value pairs in their original insertion order.

  • Values mapped to existing keys can be overwritten later.
  • Keys/values can either be an object or a variable of any data type.
  • Maps are directly iterable whereas objects are not.

Syntax

A map can be defined with the new keyword. The example below creates an empty Map object, map:

const map = new Map();

Example

To create a non-empty Map object, an array of arrays is passed into Map(). Each inner array represents a key-value pair:

const hogwartsStudents = new Map([
['Gryffindor', 'Harry Potter'],
['Slytherin', 'Draco Malfoy'],
['Hufflepuff', 'Cedric Diggory'],
]);
console.log(hogwartsStudents);

The output will be:

Map(3) {
  'Gryffindor' => 'Harry Potter',
  'Slytherin' => 'Draco Malfoy',
  'Hufflepuff' => 'Cedric Diggory'
}

Codebyte Example

In the example below, an addressBook maps a person’s name to a phone number. By the end of the program:

Code
Output
Loading...

Map

.delete()
Removes the entry associated with a given key from a Map object.
.get()
Retrieves a value associated with a given key in a Map object.
.has()
Returns a boolean reflecting whether an entry with a given key exists in a Map object.
.set()
Stores or updates entries of key-value pairs in a Map object.
.size
Returns the number of entries inside of a Map object.

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn JavaScript on Codecademy