How to get the Length of a Set in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 19, 2021

banner

Photo from Unsplash

Get the Length of a Set in JavaScript #

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.

index.js
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.

index.js
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.

index.js
const arr = ['a', 'b', 'c']; console.log(arr.length); // 👉️ 3 arr.length = 10; console.log(arr.length); // 👉️ 10

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.