Broad Network


Set and WeakSet in ECMAScript 2015

ECMAScript Sets and Maps – Part 1

ECMAScript 6

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

By: Chrysanthus Date Published: 15 Jul 2016

Introduction

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

Pre-Knowledge
At the bottom of this page, you will find links to the different series you should have read before coming here, to better understand this one.

Set

A set is like an array object, but the values are unique. The values in a set do not have to be of the same type. A value can be any primitive value or an object.

Creating a Set
The syntax to create a set is:

    setObject = new Set([iterable]);

where [iterable] is optional and can be an array. setObject is a name of your choice. The syntax to add a value to a set is:

    setObject.add(value);

If you do not want to be adding values one by one, then you can use an array to create a set as follows:

        empArr = ["John", "Mary", "Peter", "Augustine", "Angela"];

        setObj = new Set(empArr);

where setObj is a set of 5 employees in a firm.

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. If the value is an identifier, the identifier does not also have to be in quotes.

Prototype Properties of a Set
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.

Set.prototype.values()
Returns a new Iterator object that contains the values for each element in the Set object in insertion order (order in which the values were inserted). 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">

        empArr = ["John", "Mary", "Peter", "Augustine", "Angela"];

        setObj = new Set(empArr);

        iter = setObj.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).

Set.prototype.add(value)
Appends a new element with the given value to the Set object. Returns the Set object. Read and try the following code:

        setObj = new Set();

        setObj.add("John");
        setObj.add("Mary");
        setObj.add("Peter");
        setObj.add("Augustine");
        setObj.add("Angela");

        iter = setObj.values();

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

Set.prototype.size
Returns the number of values in the Set object. Read and try the following code:

        empArr = ["John", "Mary", "Peter", "Augustine", "Angela"];

        setObj = new Set(empArr);

        len = setObj.size;

        alert(len);

The output is 5.

Set.prototype.has(value)
Returns a boolean asserting whether an element is present with the given value in the Set object or not. Read and try the following code:

        empArr = ["John", "Mary", "Peter", "Augustine", "Angela"];

        setObj = new Set(empArr);

        bool = setObj.has("Mary");

        alert(bool);

The output is true. The search is case sensitive.

Set.prototype.clear()
Removes all elements from the Set object. Read and try the following code:

        empArr = ["John", "Mary", "Peter", "Augustine", "Angela"];

        setObj = new Set(empArr);

        setObj.clear();

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

The output is nothing. Note the use of for-of on the Set object.

Set.prototype.delete(value)
Removes the element associated with the value and returns the value that Set.prototype.has(value) would have previously returned. Set.prototype.has(value) will return false afterwards. Read and try the following code:

        empArr = ["John", "Mary", "Peter", "Augustine", "Angela"];

        setObj = new Set(empArr);

        setObj.delete("Mary");

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

The output does not have “Mary”.

Set.prototype.forEach(callbackFn[, thisArg])
Calls callbackFn once for each value present in the Set 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 value in the set.

        empArr = ["John", "Mary", "Peter", "Augustine", "Angela"];

        setObj = new Set(empArr);

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

Here, function is a reserved word; value is a name of your choice and represents each value in the set.

That is it for Set. We now continue with WeakSet.

WeakSet

A weak set is a set where all the values are objects. The syntax to create a weak set is:

    weakSetObject = new WeakSet([iterable]);

where [iterable] may be an array and it is optional.

An object of WeakSet has the following properties:

WeakSet.prototype.add(value)
Appends a new object with the given value to the WeakSet object.

WeakSet.prototype.delete(value)
Removes the element associated with the value. WeakSet.prototype.has(value) will return false afterwards.

WeakSet.prototype.has(value)
Returns a boolean asserting whether an element is present with the given value in the WeakSet object or not.

Read and try the following code:

    <script type="text/ECMAScript">

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

        arr = [obj1, obj2, obj3];

        weakSetObj = new WeakSet(arr);

        bool = weakSetObj.has(obj2);

        alert(bool);

    </script>

The output is true.

Another difference between Set and WeakSet is that references to objects in the WeakSet collection are held weakly. If there is no other reference to an object stored in the WeakSet, they can be garbage collected. That also means that there is no list of current objects stored in the collection. WeakSets are not enumerable.

That is it for this part of the series. We stop here and continue in the next part.

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

NEXT

Comments

Become the Writer's Follower
Send the Writer a Message