Why is WeakMap clear() method deprecated?

It is deprecated because it prevents inverted implementation of WeakMap.

See Removal of WeakMap/WeakSet clear.

If WeakMaps/WeakSets are not inspectable (via iteration) and do not have a clear operation, then the inverted implementation technique can be use used. This technique eliminates significant GS complexity.

Inverted implementation description, from the same source:

design for an inverted implementation:

Every object internally maintains a table (probably a hash table if it contains more than a few elements) that is used to implement WeakMap/Set. Entry in the table is a key/value pair where the key is a WeakMap/Set instance. Values are arbitrary ES values. Let's call such a table an "inverted map" and generically refer to such WeakMaps/Sets as WCs.


“The mapping from weakmap/key pair value can only be observed or affected by someone who has both the WeakMap and the key. With clear(), someone with only the WeakMap would’ve been able to affect the WeakMap-and-key-to-value mapping.”

Mark Miller

The reason for this restriction are security concerns:

A key property of Weak Maps is the inability to enumerate their keys. This is necessary to prevent attackers observing the internal behavior of other systems in the environment which share weakly-mapped objects. Should the number or names of items in the collection be discoverable from the API, even if the values aren't, WeakMap instances might create a side channel where one was previously not available.

tc39wiki

A enumerable WeakMap could possibly also affect GC, since you could then observe the GC process indirectly. Thus, to ensure a predictable design clear was removed as well.