How to get the Length of a Set in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20211 min read

banner

Photo by Artem Kovalev

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee