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,
- Create a new Set object
set
with initial values. - Use the
size
property to get the number of values in theset
. - 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,
- Create a new Set object
set
with initial values. - Use the
add()
method to add new values to theset
. - Use the
size
property to get the updated number of values in theset
. - 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,
- Create a new Set object
set
with initial values. - Use the
delete()
method to remove values from theset
. - Use the
size
property to get the updated number of values in theset
. - 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.