JavaScript Set size
Syntax & Examples

Set.size property

The size property of the Set object in JavaScript returns the number of values in the Set object.


Syntax of Set.size

The syntax of Set.size property is:

Set.prototype.size

This size property of Set returns the number of values in the Set object.

Return Type

Set.size returns value of type number.



✐ Examples

1 Using size to get the number of elements in a Set

In JavaScript, we can use the size property to get the number of values in a Set object.

For example,

  1. Create a new Set object set with initial values.
  2. Use the size property to get the number of values in the set.
  3. Log the result to the console using console.log().

JavaScript Program

const set = new Set(['a', 'b', 'c']);
const size = set.size;
console.log(size);

Output

3

2 Using size after adding values to a Set

In JavaScript, we can use the size property to get the number of values in a Set object after adding values.

For example,

  1. Create a new Set object set with initial values.
  2. Use the add() method to add new values to the set.
  3. Use the size property to get the updated number of values in the set.
  4. Log the result to the console using console.log().

JavaScript Program

const set = new Set(['a', 'b']);
set.add('c');
const size = set.size;
console.log(size);

Output

3

3 Using size after deleting values from a Set

In JavaScript, we can use the size property to get the number of values in a Set object after deleting values.

For example,

  1. Create a new Set object set with initial values.
  2. Use the delete() method to remove values from the set.
  3. Use the size property to get the updated number of values in the set.
  4. Log the result to the console using console.log().

JavaScript Program

const set = new Set(['a', 'b', 'c']);
set.delete('b');
const size = set.size;
console.log(size);

Output

2

Summary

In this JavaScript tutorial, we learned about size property of Set: the syntax and few working examples with output and detailed explanation for each example.