Map and Set Objects in ES6
Sunday, July 23rd, 2017
Map is a useful tool in EcmaScript-6. It allows developers to store information using key-value pairs. In EcmaScript-5 the Object Literals also served a similar purpose but there are certain differences between the two which makes Map more efficient to use.
Map (EcmaScript -6)
Object Literal (EcmaScript- 5)
Can return the size of the map via ‘.size()’ method.
The object needs to be manually iterated over to get the overall size.
Can take object, function, string, Symbol and any primitive as keys.
Can only take string and symbol as keys.
Keys will not collide with prototype keys.
Keys might collide with prototype keys.
Creating a Map object is very simple. In the sample code the variable 'user_active_map' is set to a new instance of Map. Then information is added to the Map object with key as 'user_01_active' and value as 'true'.
The value can be read from a Map object using '.get(<key>)' method by passing the key as an argument.
Similar to create the update operation can also use '.set(<key>, <value>)' method but then the value for the key will be overwritten.
Using the '.delete(<key>)' method any value associated with a specific key can be deleted.
WeakMap object shares CRUD methods with Map object such as '.delete(<key>)', '.set(<key>, <value>)' and '.get(<key>, <value>)'. But WeakMap is much more efficient for certain use cases.
The WeakMap can only have object as keys and the keys are weakly referenced to the values. So if the object which is used as the key is destroyed then the entire entry is removed from the WeakMap.
In the sample code above when the s set with the key as 'settings.now_playing' and value as 'true' it will persist only until the reference to the key is not destroyed. But when the key 'settings.now_playing' is deleted the entry associated with that key is also removed. entry i
The Set object stores collection of unique values of primitive type and object references.
To create a new instance of Set object the 'new Set(<Iterable>)' method can be used and in the sample code an array is passed as an argument. Passing an iterable argument loads the data into the Set which only contains unique values from the iterable.
The values in Set can be read by iterating over the iterable object returned by '.values()' method.
The set can be updated with new values using '.add(<value>)' method. Notice that adding duplicate value 'John' is ignored and the resulting 'user_Set' only has unique values.
Using the '.delete(<value>)' method values can be deleted from the Set object.
WeakSet object also shares the same CRUD operations as Set object with the exception to '.values()' method. But the WeakSet differs slightly because the type of values it can take can only be 'object' and those values are weakly referenced.
In the sample code above when the reference to 'setting;now_playing' is deleted the value inside 'weak_Set' also gets garbage collected.