What is the set.size property in JavaScript?

Overview

The set.size property in JavaScript returns the number of elements in the stack. In other words, this property is used to get the current size of the set.

The following illustration shows the visual representation of the set.size property:

Representation of the set.size function

In JavaScript, a set is a particular instance of a list in which all inputs are unique.


Note: If there are duplicates, then the set will only keep the first instance. For example: {'Tom','Alsvin','Eddie','Tom'} will result in {'Tom','Alsvin','Eddie'}.

Syntax

set_name.size
// where the set_name is the name of the set.

Parameter

This property does not require a parameter.

Return value

The set.size property returns the number of elements in the set.

Code

The code below shows how to use the set.size property in JavaScript:

const set_1 = new Set(["Tom","Alsvin", "Eddie"]);
//set containing value
console.log("The size of set_1: ",set_1.size);
//empty set
const set_2 = new Set();
console.log("The size of set_2: ",set_2.size);

Explanation

  • Line 1: We create a set with three values {'Tom','Alsvin','Eddie'} and name it set_1.

  • Line 3: We check the size of set_1, which contains elements, using set_1.size.

  • Line 6: We create an empty set i.e. set_2.

  • Line 7: We check the size of set_2, which is empty, using set_2.size.

Free Resources