Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Set size Property

JavaScript Set size Property

The Set.size property in JavaScript returns the number of elements in a Set. In other words, we can say that this property is used to get the current size of the set. If the Set is empty the size of the set will be returned as 0.

Syntax:

mySet.size

Return Type: Number of elements in the set

Here are some examples to illustrate the size property of the JavaScript Set object:

Example 1: In this example, we will see the use of the Javascript Set.size property.

Javascript




// Create a new set using Set() constructor
let myset = new Set();
  
// Append new elements to the
// set using add() method
myset.add(23);
myset.add(12);
  
// Print the modified set
console.log(myset);
  
// As the set has 2 elements,
// it will return 2.
console.log(myset.size);


Output:

Set(2) { 23, 12 }
2

Example 2: In this example, we will see the use of the Javascript Set.size property.

Javascript




// Creating a new set
let myset = new Set();
  
// Adding new elements to the set
myset.set('Manchester');
myset.add('London');
myset.add('Norwich');
  
// As set has 3 elements, it will return 3
console.log(set.size);


Output:

3

Supported Browsers:

  • Google Chrome
  • Firefox
  • Opera
  • Edge
  • Safari

We have a complete list of Javascript Set methods, to check those please go through the Sets in Javascript article.

RELATED ARTICLES

Most Popular

Recent Comments