DEV Community

Cover image for Lessons from opensource: Weakmap in Javascript

Lessons from opensource: Weakmap in Javascript

Ramu Narasinga on March 05, 2024

This lesson is picked from next-mdx open source code. In this article, you will learn what a WeakMap in Javascript is. WeakMap A Weak...
Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

The description on MDN is accurate, but definitely not meant for beginners. A more beginner-friendly way of explaining it would probably start with the problem being solved, which is that:

When using a Map to associate some value with an object, as long as the object is in the map and the map itself can be reached, the object won't ever be garbage-collected

The way WeakMap fixes this is simply by not preventing its keys from being collected. They don't let you loop over keys, all you can do is index them and you either get a value or you don't.

Caches for things like function memoisation or similar stuff are an application where you will typically find weak data structures like this.

Collapse
 
ramunarasinga profile image
Ramu Narasinga • Edited

Hey, quite insightful comment. Thank you.