Set.prototype.clear()
set.clear() Returns:
undefined · Updated March 13, 2026 · Map and Set set clear empty reset
The clear() method removes all elements from a Set object in a single operation. It’s the most efficient way to empty a collection when you need to preserve the same Set reference.
Syntax
set.clear()
Parameters
None. This method takes no arguments.
Return Value
Returns undefined. Unlike delete(), which returns a boolean, clear() always returns undefined because it operates on all elements at once.
Examples
Basic Usage: Empty a Set
const colors = new Set(['red', 'green', 'blue']);
console.log(colors.size); // 3
colors.clear();
console.log(colors.size); // 0
console.log([...colors]); // [Global_Objects::eval]
Event Listener: Reset State
In event-driven applications, clear() is useful for resetting collection state:
const activeUsers = new Set();
// Simulate users joining
activeUsers.add('alice');
activeUsers.add('bob');
activeUsers.add('charlie');
function handleSessionReset() {
// Clear all active users when session ends
activeUsers.clear();
console.log('Session reset. Active users:', activeUsers.size);
// Session reset. Active users: 0
}
// Later, when session expires
handleSessionReset();
This pattern is common in:
- Chat applications (clear unread messages)
- Shopping carts (clear after checkout)
- Form handling (reset selected items)
clear() vs Reassigning to a New Set
Both approaches empty a collection, but they differ in behavior:
// Approach 1: Using clear()
const set1 = new Set([1, 2, 3]);
const originalReference = set1;
set1.clear();
console.log(set1.size); // 0
console.log(set1 === originalReference); // true (same object)
// Approach 2: Reassigning to a new Set
let set2 = new Set([1, 2, 3]);
const newReference = set2;
set2 = new Set(); // New object
console.log(set2.size); // 0
console.log(set2 === newReference); // false (different object)
Memory Performance Implications
When to Use clear()
- Preserving references: If other parts of your code hold a reference to the Set,
clear()keeps that reference valid - Object pooling: Reuse the same Set instance to reduce garbage collection pressure in high-frequency scenarios
// Reusing a Set in a game loop
const bulletPool = new Set();
function spawnBullet(id) {
bulletPool.add(id);
}
function updateGame() {
// Clear bullets each frame, but keep the same Set
bulletPool.clear();
// Add new bullets...
}
When to Create a New Set
- Breaking references: When you want to ensure all stale references become obsolete
- Letting GC collect: If the old Set is no longer referenced, creating a new one lets the garbage collector reclaim memory
function processBatch(items) {
// Each batch gets a fresh Set
const processed = new Set(items);
// Process items...
// When this function ends, the Set becomes eligible for GC
return results;
}
In most cases, the performance difference is negligible. Choose based on whether you need to preserve the reference.
Common Patterns
Periodic Cache Refresh
const cache = new Set();
function addToCache(key) {
cache.add(key);
}
function refreshCache() {
// Clear stale entries on schedule
cache.clear();
console.log('Cache refreshed');
}
Cooperative Multi-tasking
const pendingTasks = new Set();
// Yield control and clear pending tasks
function yieldAndClear() {
pendingTasks.clear();
// Checkpoint for async operations
}
Gotchas
- Returns
undefined, not the emptied Set - Modifies the Set in-place; does not create a new object
- All references to the Set point to the same (now empty) instance
See Also
- set::delete — remove a single element
- Set — full Set API reference