What is a Map in JavaScript?
Map is a collection of key/value pairs that can use any type of data as a key or a value and remember the order of its entries. It is used to iterate over all the elements in an array, which results in a new array. In other words, you can take an array, make changes to the elements, and get a new array based on what is returned by the function. This is why map is useful for fast searching and looking up data.
How to Use Map in JavaScript?
Once we know how to create maps with JavaScript, there are a lot of things we can do with them.
Iterate through maps
First, let’s learn about iteration through maps. There are 3 methods we can use:
map.keys()
: returns an iterable for keysmap.entries()
: returns an iterable for entries[key, value]
map.values()
: returns an iterable for values
We can iterate over the collection of keys and values with the entries()
method, which returns an iterable, so we can use the enhanced for loop
along with destructuring.
For example, below, we extract the name and score for each key-value pair:
'use strict';
//START:DEFINE
const scores =
new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);
scores.set('Jake', 14);
//END:DEFINE
for(const [name, score] of scores.entries()) {
console.log(`${name} : ${score}`);
}
We can also use the forEach
method, which is an internal iterator.
'use strict';
//START:DEFINE
const scores =
new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);
scores.set('Jake', 14);
//END:DEFINE
scores.forEach((score, name) => console.log(`${name} : ${score}`));
The first parameter that the function receives is the value for a key that appears as the second parameter. The same forEach()
method can be used to iterate over only the values:
'use strict';
//START:DEFINE
const scores =
new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);
scores.set('Jake', 14);
//END:DEFINE
scores.forEach(score => console.log(score));
If you receive only one parameter, it will be the value, and if you receive two parameters, then it will stand for the value and key for each key-value pair.
Initialize a map with an iterable object
You can also pass an iterable object to the Map()
constructor:
let userRoles = new Map([
[sarah, 'admin'],
[bob, 'editor'],
[jill, 'subscriber']
]);
Get an element from a map by key
We can get an elements from a map by key with the get()
method
But if you pass a key that is not in that map, the it will return undefined.
userRoles.get(sarah); // admin
let foo = {name: 'Foo'};
userRoles.get(foo); //undefined
Get the number of elements in the map
We can use the size
property to get the number of elements in our maps.
console.log(userRoles.size); // 3
How to Convert map keys or values to array
At times, you may want to work with an array instead of an iterable object. We can use the spread operator to convert keys for each element into a new array.
var keys = [...userRoles.keys()];
console.log(keys);
This piece of code will convert the values of elements to an array:
var roles = [...userRoles.values()];
console.log(roles);
Map Properties and Methods
The following table shows a list of Map properties and methods for quick reference
Properties/Methods | Description | Returns |
set(key, value) | Appends a key/value pair to a Map | Map Object |
delete(key) | Removes a key/value pair from a Map by key | Boolean |
get(key) | Returns a value by key | value |
has(key) | Checks for the presence of an element in a Map by key | Boolean |
clear() | Removes all items from a Map | N/A |
keys() | Returns all keys in a Map | MapIterator object |
values() | Returns all values in a Map | MapIterator object |
entries() | Returns all keys and values in a Map as [key, value] | MapIterator object |
forEach() | Iterates through the Map in insertion order | N/A |
size | Returns the number of items in a Map | Number |
When to Use Map
Maps are similar to Objects in that they hold key/value pairs, but Maps have several advantages over objects:
Size - Maps have a
size
property, whereas Objects do not have a built-in way to retrieve their size.Iteration - Maps are directly iterable, whereas Objects are not.
Flexibility - Maps can have any data type (primitive or Object) as the key to a value, while Objects can only have strings.
Ordered - Maps retain their insertion order, whereas objects do not have a guaranteed order.
Due to these factors, Maps are a powerful data structure to consider. However, Objects haves some important advantages as well:
JSON - Objects work flawlessly with
JSON.parse()
andJSON.stringify()
, two essential functions for working with JSON, a common data format that many REST APIs deal with.Working with a single element - Working with a known value in an Object, you can access it directly with the key without the need to use a method, such as Map’s
get()
.
This list will help you decide if a Map or Object is the right data structure for your use case.
Thank you and have a nice day :)