Maps are keyed collections of data much like Objects, but whilst Object keys are limited to Strings and Symbols, a Map can be keyed using any data type.
Maps are not able to be created literally and therefore must be instantiated. The constructor comes with an optional Array argument that can be passed in to include entries upon instantiation. The Array elements must also be Arrays, with 2 elements, the first being the key and the second being the value.
const emptyMap = new Map(); const map = new Map([[1, 'one'], [2, 'two']]); map.get(2); // 'two'
So other than having the ability to key your data using non-string types, what other reasons may a map be of use?
One clear advantage to a Map is that it is iterable. You can use a
for...of loop where in Objects you can’t. With Objects, you can use
Object.entries which converts the Object into an Array which can then be iterated over. As this initial step has to be done with Objects, Maps are significantly more performant.
When iterating over Object keys or values, they are not ordered. However with a Map, they are ordered by insertion. If this is important then a Map is for you.
With a Map, the size is updated and can be retrieved with the
size property. However with an Object this has to be calculated each time we need it, using something like
Object.keys(obj).length(). If we need to know the size often, then not having to compute that ourselves may prove benefitial, especially if the collection has the potential to be large.
WeakMaps are also another data stucture available to us. WeakMaps are similar to a standard Map, with the difference being that the keys must only be Objects and are weakly referenced. What this means is that the garbage collector can do it’s job if you forget to delete your Objects (using the
delete keyword or setting to
undefined). A good explanation can be found at https://stackoverflow.com/a/29416340.
Sets are lists much like Arrays, except that they only contain unique values.
The constructor takes in an optional argument that must be an iterable. The elements of the iterable are added to the Set.
const emptySet = new Set(); const set = new Set([1 ,2 ,3]); set.has(2); // true
The biggest difference between an Array and Set is that an Array is an indexed collection whereas a Set is a keyed collection much like an Object or Map.
If your Array is significantly large, a Set may offer performance improvements, you can see some performance test results here and here.
A WeakSet data structure is also available, which only allows Objects to be added as values and are stored weakly. Without a reference to an added Object, we can let the garbage collector do it’s magic similarly to a WeakMap.