Map
BrandonDusch580 total contributions
Published Nov 5, 2021Updated Dec 31, 2021
Contribute to Docs
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:
- Tom has moved and deleted their phone number with the
.delete()
method. - Paul has changed their phone number using the
.set()
method.
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.
All contributors
- BrandonDusch580 total contributions
- Anonymous contributorAnonymous contributor3071 total contributions
- Anonymous contributorAnonymous contributor1 total contribution
- BrandonDusch
- Anonymous contributor
- Anonymous contributor
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.