jsguides

Map.prototype.clear()

map.clear()

The Map.prototype.clear() method removes all key-value pairs from a Map object, instantly resetting it to an empty state. This is useful when you need to reset a cache, clear accumulated data, or reuse a Map instance for a new set of entries. The method operates in-place and returns undefined.

Syntax

map.clear()

Parameters

This method takes no parameters. Because clear() operates on the entire Map at once, there is no need for arguments — it simply removes everything that is currently stored. This makes the call site unambiguous and self-documenting.

Return value

Returns undefined. The Map is modified in-place — there is no return value to check, because the operation always succeeds for any Map instance, empty or populated. If you need to know how many entries were removed, check map.size before calling clear().

Examples

Basic usage

const fruits = new Map();

fruits.set('apple', 5);
fruits.set('banana', 3);
fruits.set('orange', 8);

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

fruits.clear();

console.log(fruits.size); // 0

The basic pattern is straightforward: populate a Map with entries, then call clear() to remove them all at once. This is simpler than iterating and deleting each key individually, and it communicates intent more directly to anyone reading the code.

Clearing after processing

const cache = new Map();

// Populate cache with expensive computations
function getCachedData(key) {
  if (cache.has(key)) {
    return cache.get(key);
  }
  const data = computeExpensiveData(key);
  cache.set(key, data);
  return data;
}

// Later, clear the entire cache
cache.clear();

Calling clear() after a batch of cached operations is common in request handlers and data pipelines. Rather than managing individual cache entries, you empty the entire cache when the context changes — for example, when a user logs out or when a new data snapshot arrives.

Common patterns

Cache reset pattern

The most common use for clear() is resetting a cache:

class DataManager {
  constructor(maxSize = 100) {
    this.cache = new Map();
    this.maxSize = maxSize;
  }

  get(key) {
    if (this.cache.has(key)) {
      const value = this.cache.get(key);
      // Move to end (most recently used)
      this.cache.delete(key);
      this.cache.set(key, value);
      return value;
    }
    return null;
  }

  set(key, value) {
    // Evict oldest if at capacity
    if (this.cache.size >= this.maxSize) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    this.cache.set(key, value);
  }

  reset() {
    this.cache.clear();
  }
}

const manager = new DataManager(3);
manager.set('a', 1);
manager.set('b', 2);
manager.set('c', 3);

manager.reset(); // Cache is now empty

This pattern wraps a Map inside a class that enforces a capacity limit and provides a named reset() method. The method name makes the intent obvious — unlike raw map.clear(), manager.reset() tells the reader that the entire cache is being invalidated, not just cleaned up incidentally.

Session data management

class SessionStore {
  constructor() {
    this.userData = new Map();
  }

  setSession(userId, data) {
    this.userData.set(userId, {
      ...data,
      loginTime: Date.now()
    });
  }

  endSession(userId) {
    this.userData.delete(userId);
  }

  logoutAll() {
    // Clear all active sessions
    this.userData.clear();
  }

  isEmpty() {
    return this.userData.size === 0;
  }
}

const sessions = new SessionStore();
sessions.setSession('user1', { name: 'Alice' });
sessions.setSession('user2', { name: 'Bob' });

sessions.logoutAll(); // All users logged out

Session management often needs both individual invalidation (endSession) and bulk invalidation (logoutAll). Using clear() for the bulk operation is efficient and avoids a loop over all entries, which matters when the session store grows large over time.

Clear vs reassign

There are two ways to empty a Map:

const map = new Map([['a', 1], ['b', 2]]);

// Method 1: clear() - modifies existing Map
map.clear();
// map.size === 0, map still references the same object

// Method 2: Reassign to new Map
const map2 = new Map([['a', 1], ['b', 2]]);
map2 = new Map();
// Creates new Map, old one may be garbage collected

The clear() method is preferred when you want to:

  • Keep the same Map reference
  • Avoid creating a new object The clear() method is preferred when you want to:
  • Keep the same Map reference
  • Avoid creating a new object
  • Explicitly signal “emptying” in code

Reassignment (map = new Map()) is better when you want to sever the old Map entirely — for example, when other code should not be able to observe the reset through a shared reference. The two approaches serve different ownership models, so choose based on whether the Map is shared or private.

Periodic cleanup

const temporaryData = new Map();

// Add data with timestamps
temporaryData.set('task1', { data: 'result', timestamp: Date.now() });
temporaryData.set('task2', { data: 'result', timestamp: Date.now() });

function cleanupOldEntries(maxAge = 3600000) {
  const now = Date.now();
  for (const [key, value] of temporaryData) {
    if (now - value.timestamp > maxAge) {
      temporaryData.delete(key);
    }
  }
}

// Clear everything after processing
function finishBatch() {
  const count = temporaryData.size;
  temporaryData.clear();
  return `Processed ${count} entries`;
}

Periodic cleanup often combines two strategies: age-based eviction using delete() for granular control, and clear() for wholesale reset at the end of a processing cycle. The finishBatch function demonstrates how clear() can serve as an explicit “done” signal after all individual entries have been handled.

Event listener management

class EventEmitter {
  constructor() {
    this.listeners = new Map();
  }

  on(event, callback) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, []);
    }
    this.listeners.get(event).push(callback);
  }

  removeAllListeners(event) {
    if (event) {
      this.listeners.delete(event);
    } else {
      // Remove all listeners for all events
      this.listeners.clear();
    }
  }
}

const emitter = new EventEmitter();
emitter.on('click', () => console.log('clicked'));
emitter.on('hover', () => console.log('hovered'));

// Clear all listeners
emitter.removeAllListeners();

Event emitters built on Map can remove listeners by event name using delete() or remove everything using clear(). Calling clear() with no argument is a clean way to implement removeAllListeners() for teardown or hot-reload scenarios.

Performance

Map.prototype.clear() runs in O(n) time — it must release references to all stored keys and values so the garbage collector can reclaim them. In contrast, reassigning the variable to new Map() is O(1) for the assignment itself, but the old Map’s entries must still be garbage-collected eventually. For long-running applications that reuse the same Map instance, clear() is the idiomatic choice and avoids the overhead of allocating a new Map object on each reset cycle.

clear() does not affect other references

If other variables hold a reference to the same Map, clear() empties the Map for all of them. This is intentional when using a shared cache, but can be surprising if unintended sharing exists.

const shared = new Map([['a', 1]]);
const alias = shared;

shared.clear();
console.log(alias.size); // 0 — same Map object

When to use clear() vs creating a new Map

clear() empties the existing Map object in place, which means all other variables holding a reference to the same Map also see it become empty. If you want to start fresh while keeping the old data available elsewhere, assign a new Map to your variable instead. Use clear() when you specifically need to reset the shared object — for example, when the Map is held in a module-level cache that multiple callers share and you need to invalidate it on logout or refresh.

See also