jsguides

Set.prototype.clear()

set.clear()

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. There is no partial-clear variant and no return value to check—the operation either succeeds or throws. After clear() runs, the Set is guaranteed to be empty with size zero.

Examples

Basic usage: emptying a Set

const colors = new Set(['red', 'green', 'blue']);

console.log(colors.size); // 3

colors.clear();

console.log(colors.size); // 0
console.log([...colors]); // []

Event listener: resetting state

The simplest use of clear() is emptying a collection you own entirely. When a Set is shared with other parts of the application, resetting it through clear() keeps every observer in sync. This pattern shows up often in event-driven code where multiple handlers need to agree on the current 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—and picking the wrong one can break code that holds a reference to the original Set.

// 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

Choosing between clear() and reassignment also affects memory behavior. The right choice depends on whether other code holds a reference to the same Set instance.

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

Creating a fresh Set instance is the right call when no other code depends on the original object. It simplifies reasoning about ownership and lets the garbage collector do its job.

  • 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.

Clearing in shared state

clear() matters most when a Set is shared across functions, modules, or event handlers. If one part of the app keeps a reference to the Set while another part resets it, clear() preserves that shared reference and updates every observer at once. That makes it a good fit for stateful UI code, caches, and request trackers where replacing the Set would leave stale references behind. If you want the rest of the program to keep looking at the same collection, clear() is the safer reset operation.

Empty set versus new instance

Creating a new Set is simpler when the old instance is no longer needed at all. Clearing is better when the identity of the Set object matters. That distinction comes up in tests, dependency injection, and long-lived services that expose the Set to callers. A new instance breaks object identity, while clear() keeps identity stable. If you are not sure which one to use, ask whether any other code stores the Set object itself rather than just its contents.

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');
}

Clearing a cache on a schedule is the simplest pattern. When you also need to coordinate with async checkpoints or yield control in a cooperative scheduler, clear() acts as a reset boundary that other tasks can observe before taking their next step.

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