JavaScript Map
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
- .clear()
- Removes all key-value pairs from a Map object.
- .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.
- .keys()
- Returns a new map iterator object that contains the keys of each element in the map.
- .set()
- Stores or updates entries of key-value pairs in a Map object.
- .size
- Returns the number of entries inside of a Map object.
- .values()
- Returns a new iterator object that contains the values of a Map object in insertion order.
- entries()
- Returns an iterator of the key–value pairs in a Map object.
Contribute to Docs
- 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.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours