Last updated: Mar 2, 2024
Reading timeยท2 min
Use the size
property to get the length of a Set, e.g. mySet.size
. The
size
property returns the number of values in the Set
object.
When accessed on an empty Set
, the size
property returns 0
.
const set = new Set(['a', 'b', 'c']); console.log(set.size); // ๐๏ธ 3 set.add('d'); set.add('e'); console.log(set.size); // ๐๏ธ 5
We used the
Set.size
property to get the number of elements in the Set
object.
length
property and returns an integer representing how many elements the Set
contains.As opposed to the array's length
property, the size
property is read-only
and can't be changed by the user.
const set = new Set(['a', 'b', 'c']); console.log(set.size); // ๐๏ธ 3 set.size = 10; console.log(set.size); // ๐๏ธ 3
Even though we tried to update the size of the Set
, we were unable to.
This is not the case when using the array's length
property.
const arr = ['a', 'b', 'c']; console.log(arr.length); // ๐๏ธ 3 arr.length = 10; console.log(arr.length); // ๐๏ธ 10
The code sample shows that we can update the array's length and contents by
using its length
property.
As expected, the size of the Set
object is updated when:
Set
Set
Set.clear()
method to remove all elements from the Set
const set = new Set(); console.log(set.size); // ๐๏ธ 0 // โ add elements to the Set set.add('bobby'); set.add('hadz'); console.log(set.size); // ๐๏ธ 2 // โ delete an element from the set set.delete('bobby'); console.log(set.size); // ๐๏ธ 1 // โ clear the set object set.clear(); console.log(set.size); // ๐๏ธ 0
We used the
Set.add()
method to add 2 elements to the Set
object.
Accessing the size
property on the Set
returns 2
at this point.
We used the Set.delete() method to
remove an element from the Set
.
Accessing the size
property returned 1
after removing the element.
Finally, we used the
Set.clear()
method to remove all elements from the Set
, so the size
property returned
0
.
Set
using Set.forEach()
You can also use the Set.forEach()
method to get the length of a Set
.
const set = new Set(); console.log(set.size); // ๐๏ธ 0 set.add('bobby'); set.add('hadz'); let length = 0; set.forEach(_element => { length += 1; }); console.log(length); // ๐๏ธ 2
We declared a length
variable and used the Set.forEach()
method to iterate
over a Set
.
On each iteration, we increment the length
variable by 1
to get the total
length of the Set
.
Note that the length
variable has to be declared using let
because variables
declared using const
cannot be reassigned.
However, most of the time using the forEach()
method is not necessary because
the Set.size
property does exactly what we need and gets automatically
updated.
You can learn more about the related topics by checking out the following tutorials: