How it works...

Like instances of Map, the WeakMap instance is a pairing between a key and value. However, crucially, they differ in what types can be used as keys. Map can use any type for keys. WeakMap can only have values of the Object type as keys. This helps WeakMap to be more efficient.

The reason that WeakMap can be more efficient has to do with memory management and garbage collection. Consider that Map entries have to be kept around for the lifetime of the program. Since they can use primitive types as keys (Booleans, strings, numbers, and Symbols), these values could be recreated, and those Map entries can be referenced at any time.

WeakMap keys, by contrast, can only be of the Object type. The Object values cannot be recreated; ...

Get ECMAScript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.