Course contentsShow
← JavaScript
Lesson 1048 of 2,72324. Maps and SetsFree lesson

Set Size and Clearing

Access the size property and use clear() to remove all elements from a Set.

Set Size and Clearing

You'll learn how to check how many elements a Set contains and how to remove all elements at once.

Understanding Set Size

Just like Maps, Sets have a size property that tells you exactly how many unique elements are stored inside. This is similar to an array's length, but remember: Sets only count unique values.

const fruits = new Set(['apple', 'banana', 'orange']);
console.log(fruits.size); // 3

fruits.add('grape');
console.log(fruits.size); // 4

fruits.add('apple'); // Already exists, no change
console.log(fruits.size); // Still 4

Notice that size is a property, not a method, so you don't call it with parentheses.

Clearing All Elements

When you need to empty a Set completely, use the clear() method. It removes every element in one operation:

const colors = new Set(['red', 'blue', 'green']);
console.log(colors.size); // 3

colors.clear();
console.log(colors.size); // 0
console.log(colors.has('red')); // false

Think of clear() like dumping out a jar of marbles—the jar (Set) still exists, but it's now completely empty.

Practical Usage

const uniqueVisitors = new Set();
uniqueVisitors.add('user123');
uniqueVisitors.add('user456');
uniqueVisitors.add('user123'); // Duplicate, ignored

console.log(`Total unique visitors: ${uniqueVisitors.size}`); // 2

// End of day: reset the counter
uniqueVisitors.clear();
console.log(`After reset: ${uniqueVisitors.size}`); // 0

Key Takeaway: Use the size property to count unique elements in a Set, and call clear() to remove all elements at once—the Set remains usable but empty.