javascriptecmascript-6weakmap

Why is WeakMap clear() method deprecated?


I have been working with WeakMaps in JavaScript, and after checking the documentation I realized that the clear method has been deprecated / removed from ECMAScript 6.

What is the reason for this? Why force us to do a clear function like:

clear() {
  this._weakmap = new WeakMap()
}

Solution

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