Skip to content

JavaScript sets | Object

  • by

JavaScript sets Object is a collection of unique values. It stores unique values of any type, whether primitive values or object references.

To create a new empty Set use the following syntax:

let setObject = new Set();

Optional you can pass an iterable object to the Set constructor, all the elements of the iterable object will be added to the new set:

let setObject = new Set(iterableObject);

JavaScript sets

Simple example code creates a new Set from an Array.

<!DOCTYPE html>
<html>
<body>
  <script>
    var arr = ['a', 'a', 'b', 'c', 'c'];
    let chars = new Set(arr);

    console.log(chars)
    console.log(typeof(chars))
  </script>
</body>
</html>

Output: All elements in the set must be unique therefore it  chars only contains 3 distinct elements a, b and c.

JavaScript sets Object

Looping the elements of a JavaScript Set

// Create a Set
const letters = new Set(["a","b","c"]);

// List all entries
let text = "";
letters.forEach (function(value) {
  text += value;
})

Set Methods

MethodsDescription
add()It adds the specified values to the Set object.
clear()It removes all the elements from the Set object.
delete()It deletes the specified element from the Set object.
entries()It returns an object of Set iterator that contains an array of [value, value] for each element.
forEach()It executes the specified function once for each value.
has()It indicates whether the Set object contains the specified value element.
values()It returns an object of Set iterator that contains the values for each element.

Do comment if you have any doubts or suggestions on this JS code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading