Skip to content

JavaScript set length | Example code

  • by

Use the size property to get the length of a Set in JavaScript. The size accessor property returns the number of elements in a Set object.

mySet.size;

Note: the size property is read-only and can’t be changed by the user.

Javascript set length

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    const set = new Set(['a', 'b', 'c']);
    console.log(set.size);

    set.add('d');
    set.add('e');
    console.log(set.size); 
  </script>
</body>
</html>

Output:

JavaScript set length

More example

const set1 = new Set();
const object1 = {};

set1.add(42);
set1.add('forty two');
set1.add('forty two');
set1.add(object1);

console.log(set1.size); // 3

This property, unlike Array.prototype.length, is read-only, which means that you can’t change it by assigning something to it:

mySet.size = 5;
mySet.size; // 4

In strict mode it even throws an error:

TypeError: Cannot set property size of #<Set> which has only a getter

Do comment if you have any doubts or suggestions on this Js set topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *