Broad Network


Map and WeakMap in ECMAScript 2015

ECMAScript Sets and Maps – Part 2

ECMAScript 6

Foreword: In this part of the series, I talk about the map and weak map in ECMAScript.

By: Chrysanthus Date Published: 15 Jul 2016

Introduction

This is part 2 of my series, ECMAScript Sets and Maps. In this part of the series, I talk about the map and weak map in ECMAScript.

A map is like a two-dimensional array of two columns. Each cell in each row can have a primitive value or an object. All the items in the first column are called keys. All the items in the second column are called values. In each row a key corresponds to its value. So a map consists of key/value pairs.

A Map Content Example
The following list shows some fruits and their colors:

Apple, purple
Banana, yellow
Pear, green
Lemon, green

In the list we see that apple is purple, banana is yellow, etc. Apple is key for the value, purple; Banana is key for the value, yellow; etc.

Map

Creating a Set
The syntax to create a map is:

    mapObject = new Map([iterable]);

where [iterable] is optional and can be a 2D array of two columns. mapObject is a name of your choice. The syntax to add a key/value pair to a map is:

    mapObject.set(key, value);

If you do not want to be adding key/value pairs one by one, then you can use a two-dimensional array of two columns to create the map as follows:

        fruits = [['Apple', "purple"], ['Banana', "yellow"], ['Pear', "green"], ['Lemon', "green"]];

        mapObj = new Map(fruits);

where mapObj is a map of 4 fruits to their colors.

Now that values in a set have to be unique, if you try to add the same value more than once, what will happen? - Answer: the set will simply not accept the duplicate.

Note: if the value is a number, the number does not have to be in quotes.

Prototype Properties of a Map
An object property is known as prototype property. In the syntax you see the word, prototype, but in the code you do not use the word, prototype.

Map.prototype.values()
Returns a new Iterator object that contains the values for each element in the Map object in insertion order. The return iterator object is not really an array, so to read the values out, you have to use the for-of statement.

Read and try the following code:

    <script type="text/ECMAScript">

        fruits = [['Apple', "purple"], ['Banana', "yellow"], ['Pear', "green"], ['Lemon', "green"]];

        mapObj = new Map(fruits);

        iter = mapObj.values();

        for (value of iter)
            {
                document.write(value + '<br>');
            }

    </script>

Note: value in the parentheses is an identifier of your choice, and represents the current item in the iterator. An iterator is to have a list scanned (one-by-one).

Map.prototype.set(key, value)
Sets the value for the key in the Map object (sets the key/value pair). Returns the Map object. Read and try the following code:

        mapObj = new Map();

        mapObj.set('Apple', "purple");
        mapObj.set('Banana', "yellow");
        mapObj.set('Pear', "green");
        mapObj.set('Lemon', "green");

        iter = mapObj.values();

        for (value of iter)
            {
                document.write(value + '<br>');
            }

Map.prototype.size
Returns the number of key/value pairs in the Map object.

        fruits = [['Apple', "purple"], ['Banana', "yellow"], ['Pear', "green"], ['Lemon',

"green"]];

        mapObj = new Map(fruits);

        len = mapObj.size;

        alert(len);

The output is 4.

Map.prototype.has(key)
Returns a boolean asserting whether a value has been associated to the key in the Map object or not. Read and try the following code:

        fruits = [['Apple', "purple"], ['Banana', "yellow"], ['Pear', "green"], ['Lemon', "green"]];

        mapObj = new Map(fruits);

        bool = mapObj.has('Banana');

        alert(bool);

The output is true. The search is case sensitive.

Map.prototype.get(key)
Returns the value associated with the key, or undefined if there is none. Read and try the following code:

        mapObj = new Map();

        mapObj.set('Apple', "purple");
        mapObj.set('Banana', "yellow");
        mapObj.set('Pear', "green");
        mapObj.set('Lemon', "green");

        val = mapObj.get('Banana');

        alert(val);

The output is yellow. The search is case sensitive.

Map.prototype.entries()
Returns a new Iterator object that contains a 2D array of [key, value] for each element in the Map object in insertion order. Read and try the following code:

        mapObj = new Map();

        mapObj.set('Apple', "purple");
        mapObj.set('Banana', "yellow");
        mapObj.set('Pear', "green");
        mapObj.set('Lemon', "green");

        iter = mapObj.entries();

        for ([key, value] of iter)
         {
                document.write(key + ', ' +value + '<br>');
         }

Note the use of the for-of statement. Also note the presence of the two-element array, [key, value] . key is a name of your choice and it represents the key in each key/value pair. value is a name of your choice and it represents the value in each key/value pair.

Map.prototype.keys()
Returns a new Iterator object that contains the keys for each element in the Map object in insertion order. Read and try the following code:

        mapObj = new Map();

        mapObj.set('Apple', "purple");
        mapObj.set('Banana', "yellow");
        mapObj.set('Pear', "green");
        mapObj.set('Lemon', "green");

        iter = mapObj.keys();

        for (key of iter)
         {
                document.write(key + '<br>');
         }

In the code, key is a name of your choice and it represents the key in each key/value pair.

Map.prototype.clear()
Removes all key/value pairs from the Map object. Read and try the following code:

        mapObj = new Map();

        mapObj.set('Apple', "purple");
        mapObj.set('Banana', "yellow");
        mapObj.set('Pear', "green");
        mapObj.set('Lemon', "green");

        mapObj.clear();

        mapObj.set('a key', "a value");

        for ([key, value] of mapObj)
            {
                document.write(key + ', ' +value + '<br>');
            }

Note that for-of can ve used with the map object.

Map.prototype.delete(key)
Removes any value associated to the key and returns the value that Map.prototype.has(key) would have previously returned. Map.prototype.has(key) will return false afterwards. Read and try the following code:

        mapObj = new Map();

        mapObj.set('Apple', "purple");
        mapObj.set('Banana', "yellow");
        mapObj.set('Pear', "green");
        mapObj.set('Lemon', "green");

        mapObj.delete('Banana');

        for ([key, value] of mapObj)
            {
                document.write(key + ', ' +value + '<br>');
            }

Map.prototype.forEach(callbackFn[, thisArg])
Calls callbackFn once for each key-value pair present in the Map object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the this value for each callback. [,thisArg] is optional. Read and try the following code, where callbackFn is a function that displays each ley/value pair in the map.

        mapObj = new Map();

        mapObj.set('Apple', "purple");
        mapObj.set('Banana', "yellow");
        mapObj.set('Pear', "green");
        mapObj.set('Lemon', "green");

        mapObj.forEach(function(key, value)
            {
                document.write(key + ', ' +value + '<br>');
            });

That is it for Map. We now continue with WeakMap.

WeakMap

A weak map is a map where all the keys are objects. The values can be arbitrary values (literals, objects, identifiers). The syntax to create a weak map is:

    weakSetObject = new WeakMap([iterable])

where [iterable] may be a 2D array of two columns, and it is optional.

An object of WeakMap has the following properties:

WeakMap.prototype.delete(key)
Removes any value associated to the key. WeakMap.prototype.has(key) will return false afterwards.

WeakMap.prototype.get(key)
Returns the value associated to the key, or undefined if there is none.

WeakMap.prototype.has(key)
Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.

WeakMap.prototype.set(key, value)
Sets the value for the key in the WeakMap object. Returns the WeakMap object.

Read and try the following code:

    <script type="text/ECMAScript">

        obj1 = {};
        obj2 = {};
        obj3 = {};

        colors = [[obj1, "purple"], [obj2, "yellow"], [obj3, "green"]];

        weakMapObj = new WeakMap(colors);

        bool = weakMapObj.has(obj2);

        alert(bool);

    </script>

The output is true.

Another difference between Map and WeakMap is that objects as keys are weakly referenced. The key in a WeakMap is held weakly. What this means is that, if there are no other strong references to the key, then the entire entry will be removed from the WeakMap by the garbage collector.

That is it for this part of the series.

Chrys

Related Links

ECMAScript Basics
ECMAScript Operators
Expressions in ECMAScript
Statements in ECMAScript
Custom Objects in ECMAScript
Functions in ECMAScript
ECMAScript Date Object
The ECMAScript String Object
ECMAScript String Regular Expressions
ECMAScript Template Literal
The ECMAScript Array
ECMAScript Sets and Maps
ECMAScript Number
Scopes in ECMAScript
Mastering the ECMAScript (JavaScript) eval Function
Sending Email with ECMAScript
ECMAScript Insecurities and Prevention
Advanced Course
Advanced ECMAScript Regular Expressions
Promise in ECMAScript 2015
Generator in ECMAScript 2015
ECMAScript Module
More Related Links
Node Mailsend
EMySQL API
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course

BACK

Comments

Become the Writer's Follower
Send the Writer a Message