Borislav Hadzhiev
Tue Oct 19 2021·1 min read
Photo by Artem Kovalev
Use the size
property to get the length of a Set - 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.
The property is very similar to an array's 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