JavaScript Map and WeakMap
In JavaScript, Map
is a built-in object that provides an easy way to store and manipulate data in key/value pairs.
Map vs. Object
The main difference between a Map
and an Object
in JavaScript is the type of their keys, as well as how they store and manipulate data.
Keys: In a
Map
, the keys can be any type of value, including functions, objects, or even other maps. In contrast, the keys of anObject
must always be strings or symbols.Order of properties: The properties in a
Map
are ordered based on the order in which they are inserted, whereas the order of properties in anObject
is not guaranteed.Usage:
Map
is generally used when the use of arbitrary data types in keys is required or when the order of properties is critical.Object
is used when the keys of the properties are known ahead of time and easy manipulation of object data is required.Search:
Map
provides a set of methods for working with key/value pairs usingget()
,set()
, andhas()
methods that are not available on objects.
Here is a summary comparison between the two based on some key properties:
Property | Map | Object |
Key types | Any | Strings or Symbols |
Order of properties | Ordered | Not guaranteed |
Property access | get() , set() , has() | Dot notation or bracket notation |
Examples | phone numbers, locations | properties of an object, hash table |
Using the Map object
Here is an example of how to use a Map
in JavaScript:
// create a new Map object
const myMap = new Map();
// add some key/value pairs to the map
myMap.set('apple', 1);
myMap.set('banana', 2);
myMap.set('cherry', 3);
// get the value for a specific key
console.log(myMap.get('banana')); // 2
// check if a key is in the map
console.log(myMap.has('pear')); // false
// get the number of items in the map
console.log(myMap.size); // 3
// loop through the map using a for...of loop
for (const [key, value] of myMap) {
console.log(`${key} = ${value}`);
}
// remove a key/value pair from the map
myMap.delete('cherry');
In this example, we create a new Map
object, add some key/value pairs to it using the set()
method, and then retrieve values from the map using the get()
method. We also demonstrate how to check if a key exists in the map using the has()
method, how to loop through the map using a for...of
loop, and how to remove key/value pairs from the map using the delete()
method.
Iterating Map
To iterate over a Map object in JavaScript, you can use a for...of
loop, or the forEach
method.
const myMap = new Map([
[1, { name: 'John', age: 25, hobbies: ['reading', 'golfing'] }],
[2, { name: 'Jane', age: 30, hobbies: ['skiing', 'cooking', 'reading'] }],
[3, { name: 'Jack', age: 40, hobbies: ['traveling', 'hiking', 'gardening'] }],
]);
// Method 1: Using for/of loop
for (const [key, value] of myMap) {
console.log(`Key: ${key}, Name: ${value.name}, Age: ${value.age}, Hobbies: ${value.hobbies.join(', ')}`);
}
// Method 2: Using forEach method
myMap.forEach((value, key) => {
console.log(`Key: ${key}, Name: ${value.name}, Age: ${value.age}, Hobbies: ${value.hobbies.join(', ')}`);
});
JavaScript WeakMap
WeakMap is a special type of Map object that allows developers to store weakly held object references as keys and arbitrary values as values.
In a WeakMap, object references held as keys are not counted toward the memory allocation of the map, which means that they can be garbage collected by the browser's garbage collector if they are not being used anymore.
This feature makes WeakMap a useful tool for managing memory efficiently and preventing memory leaks in large-scale applications that handle a lot of objects. However, WeakMap has some limitations, such as being unable to iterate over its keys and values or checking the size of the map.
Map vs. WeakMap
The main difference between Map
and WeakMap
in JavaScript is in how they handle the references to the keys.
Map
stores the reference of its keys and values, so they remain in memory until the Map
object itself is destroyed or explicitly cleared. This can lead to a memory leak and slow down the performance of large-scale applications.
On the other hand, WeakMap
allows the garbage collector to remove its entries when there are no other references to the keys of the map. This means that WeakMap
doesn't hold on to the underlying objects that are used as keys in the map. So if the object is deleted or loses reference from all other parts of the program, it can be garbage collected, even if it's still stored in the WeakMap
.
Here are some other key differences between Map
and WeakMap
in JavaScript:
Map
allows any type of key, including primitive types and objects, whileWeakMap
only allows objects as keys.Map
has more methods thanWeakMap
, such askeys()
,values()
, andentries()
, which allow you to iterate over its keys, values, and key-value pairs.WeakMap
only hasget()
,set()
,has()
, anddelete()
methods.Map
has asize
property that represents the number of key-value pairs in the map.WeakMap
doesn't have asize
property since it doesn't keep track of the number of entries.
In summary, Map
is useful when you want to store a large number of key-value pairs and don't need to worry about them being garbage collected, while WeakMap
is useful when you want to avoid memory leaks and only need to store a few key-value pairs associated with objects that could be garbage collected.
Conclusion
Map
and WeakMap
objects provide a more flexible and structured approach for handling and manipulating data in key-value pairs. Map
is better when there is a need to store many key-value pairs and performance is not necessarily important, while WeakMap
is better suited for when we need to store only a few key-value pairs and want to avoid memory leaks.
Subscribe to my newsletter
Read articles from Iman Rousta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Iman Rousta
Iman Rousta
Front-end developer