ES6 MapES6 is a series of new features that are added to the JavaScript. Prior to ES6, when we require the mapping of keys and values, we often use an object. It is because the object allows us to map a key to the value of any type. ES6 provides us a new collection type called Map, which holds the key-value pairs in which values of any type can be used as either keys or values. A Map object always remembers the actual insertion order of the keys. Keys and values in a Map object may be primitive or objects. It returns the new or empty Map. Maps are ordered, so they traverse the elements in their insertion order. SyntaxFor creating a new Map, we can use the following syntax: The Map () accepts an optional iterable object, whose elements are in the key-value pairs. Map Properties
Let us understand the above property of Map object in brief. Map.prototype.sizeIt returns the number of elements in the Map object. Syntax Example Output 4 Map MethodsThe Map object includes several methods, which are tabulated as follows:
Weak MapsWeak Maps are almost similar to normal Maps except that the keys in weak maps must be objects. It stores each element as a key-value pair where keys are weakly referenced. Here, the keys are objects, and the values are arbitrary values. A Weak Map object only allows the keys of an object type. If there is no reference to a key object, then they are targeted to garbage collection. In weak Map, the keys are not enumerable. So, there is no method to get the list of keys. A weak map object iterates its elements in the insertion order. It only includes delete(key), get(key), has(key) and set(key, value) method. Let us try to understand the illustration of the weak Map. ExampleOutput WeakMap { <items unknown> } true The for...of loop and Weak MapsThe for...of loop is used to perform an iteration over keys, values of the Map object. The following example will illustrate the traversing of the Map object by using a for...of loop. ExampleOutput Red Green Yellow Violet 1: Red 2: Green 3: Yellow 4: Violet Iterator and MapAn iterator is an object, which defines the sequence and a return value upon its termination. It allows accessing a collection of objects one at a time. Set and Map both include the methods that return an iterator. Iterators are the objects with the next() method. When the next() method gets invoked, the iterator returns an object along with the "value" and "done" properties. Let us try to understand some of the implementations of iterator along with the Map object. Example-1Output { value: 'Red', done: false } { value: 'Green', done: false } { value: 'Yellow', done: false } Example-2Output { value: [ '1', 'Red' ], done: false } { value: [ '2', 'Green' ], done: false } { value: [ '3', 'Yellow' ], done: false } Example-3Output { value: '1', done: false } { value: '2', done: false } { value: '3', done: false } Next TopicES6 Set |