Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Set Methods

The new Set() Method

Provide an array to the new Set() constructor:

Example

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

The add() Method

Example

letters.add(“d”);
letters.add(“e”);

If you add duplicate elements, only the first one will be stored.

Example

letters.add(“a”);
letters.add(“b”);
letters.add(“c”);
letters.add(“c”);
letters.add(“c”);
letters.add(“c”);
letters.add(“c”);
letters.add(“c”);

Listing Set Elements

You can iterate through all Set elements (values) using a for…of loop.

Example

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

// List all Elements
let text = “”;
for (const x of letters) {
  text += x;
}

The has() Method

The has() method returns true if a specified value is present in a Set.

Example

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

// Does the Set contain “d”?
answer = letters.has(“d”);

The forEach() Method

The forEach() method calls a function for each element in a Set.

Example

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

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

The values() Method

The values() method returns an Iterator object containing the values in a Set.

Example 1

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

// Get all Values
const myIterator = letters.values();

// List all Values
let text = “”;
for (const entry of myIterator) {
  text += entry;
}

Example 2

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

// List all Values
let text = “”;
for (const entry of letters.values()) {
  text += entry;
}

The keys() Method

The keys() method returns an Iterator object that contains the values in a Set.

Note

A Set has no keys, so the keys() method returns the same as the values() method.

This makes Sets compatible with Maps.

 

Example 1

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

// Create an Iterator
const myIterator = letters.keys();

// List all Elements
let text = “”;
for (const x of myIterator) {
  text += x;
}

Example 2

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

// List all Elements
let text = “”;
for (const x of letters.keys()) {
  text += x;
}

The entries() Method

The entries() method returns an Iterator with [value, value] pairs from a Set.

Note

The entries() method is intended to return a [key, value] pair from an object. However, since a Set has no keys, the entries() method returns [value, value]. This similarity makes Sets compatible with Maps.

Example 1

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

// Get all Entries
const myIterator = letters.entries();

// List all Entries
let text = “”;
for (const entry of myIterator) {
  text += entry;
}

Example 2

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

// List all Entries
let text = “”;
for (const entry of letters.entries()) {
  text += entry;
}