Useful features of Set collections
Set
collections have a number
of useful properties and methods. Let's
take a look at them.
Collection size
The size
property contains
the size of the collection:
let set = new Set;
set.add(1);
set.add(2);
set.add(3);
console.log(set.size);
Checking for a value presence
You can check if a value exists in a
collection using the has
method:
let set = new Set;
set.add(1);
set.add(2);
set.add(3);
console.log(set.has(1));
Element deletion
You can delete an element from a
collection using the delete
method:
let set = new Set;
set.add(1);
set.add(2);
set.add(3);
set.delete(1);
Clearing a collection
You can clear an entire collection
using the clear
method:
let set = new Set;
set.add(1);
set.add(2);
set.add(3);
set.clear();
Practical tasks
Create a Set
collection with
initial values 1
, 2
and 3
. Display the number
of elements in the collection.
Create a Set
collection with
initial values 1
, 2
and 3
. Check if the collection
has an element with the value 3
and then an element with value 4
.