WeakMap and Map

WeakMap and Map

WeakMap and Map are both data structures in JavaScript used for storing key-value pairs, but they have some significant differences in terms of their behavior and use cases.

MAP:

It allows you to store key-value pairs where keys can be of any data type (including objects and primitive values) and maintain the order of insertion.

Use Cases:

  • To associate values with Keys(primitive and objects)
  • If strong reference is required to Keys, so preventing from being garbage collected.

Example 1: Caching with Map


WeakMap:

It allows you to store key-value pairs where keys are only objects, and do not prevent those objects from being garbage collected when there are no other references to them

Use Cases:

  • Is often used when you need to associate metadata or auxiliary data with objects, and you want that data to be automatically removed when the associated object is no longer in use.
  • It's commonly used in situations involving private or internal data for objects.

Example 2: Event Listeners with WeakMap



HISHAM AHAMMED

Experienced Node.js Developer Skilled in Deploying Applications with Docker, Kubernetes, and Cloud Platforms

1 年

Very informative

回复
Pavan Kumar N

Software Engineer 2 @ Tellius | Backend Heavy | Banking and B2B | AI Enthusiast

1 年

It's a great informative post

要查看或添加评论,请登录

Nithin Raj的更多文章

社区洞察

其他会员也浏览了