Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Map.prototype.clear: remove every entry

The clear method removes all key–value pairs from a Map in place, makes its observed size zero, and returns undefined.

Version: ECMAScript 2015 onward; example target: Node.js 24.22.2

Syntax

map.clear()

map.clear() marks every existing Map entry empty without creating a new collection. Afterwards, size is 0 and has, get, and iteration cannot observe the removed keys. The method takes no meaningful arguments and always returns undefined, so it cannot be chained like set.

Existing iterators are not replaced. They skip cleared records, but an iterator that has not finished with done: true can observe entries added to the same Map after clear, because new records are appended to the internal sequence. Clearing removes the Map’s references to keys and values, but memory reclamation depends on other references and the garbage collector.

The method requires a receiver with Map internal data; Map.prototype.clear.call({}), a Set, or an unhandled Proxy wrapping a Map throws TypeError. It has been standard since ECMAScript 2015. Use it to preserve the identity of a Map observed elsewhere; assigning map = new Map() changes only that local reference.

Examples

const map = new Map([["a", 1], ["b", 2]]);
const keys = map.keys();
console.log(keys.next().value);

const result = map.clear();
console.log(result === undefined, map.size);

map.set("c", 3);
const afterClear = keys.next();
console.log(afterClear.value, afterClear.done);

try {
  Map.prototype.clear.call({});
} catch (error) {
  console.log(error instanceof TypeError);
}

Result

a
true 0
c false
true

Sources