We can use JavaScript to get the set size by simply using the size property of the set. The size property will simply return the number of items in the set.

var someSet = new Set(["this","is","a","set","of","size","7"]);
var length_Of_Set = someSet.size;



When you’re just starting out, this might not apply to you. However, you will quickly learn that in JavaScript, it can be useful to be able to easily calculate the size of a set. You should also carefully consider the length.

Why Sets?

Using sets in JavaScript is crucial for efficient and unique data management. Unlike arrays, sets store only unique values, preventing duplicates and streamlining data integrity. This uniqueness simplifies tasks like eliminating redundant information from collections or ensuring distinct elements in algorithmic operations. Sets also offer superior performance in certain scenarios, as they provide constant-time complexity for basic operations like insertion, deletion, and search. Leveraging sets enhances code readability by conveying intent – when a developer uses a set, it signals a specific requirement for distinct elements. This not only aids in clearer code but also fosters a more robust and reliable application architecture.

To get the size of a set in JavaScript, we can use the size property.

Let’s use our code above and create a simple function that takes a set, and returns the size of the set.

function getSetSize(someSet){
  return someSet.size;

And now let’s just see some examples of using this function to get the size of some sets.

Remember that sets differ from arrays in that they can only contain unique values.

function getSetSize(someSet){
  return someSet.size;

var someSet1 = new Set(["this","is","a","set"]);
var someSet2 = new Set(["4","5","4","5"]);
var someSet3 = new Set(["red","green","blue","red","yellow","red","orange","red"]);
var someSet4 = new Set(["false","","null","undefined",null,0,"4"]);



Hopefully this article has been useful for you to learn how to use JavaScript to get set size.

javascript set size

Categorized in:


Last Update: March 11, 2024