![]() |
In JavaScript, there are two types of references strong and weak. The WeakSet and WeakMap are called weak references. Since these are weak references they do not prevent garbage collection if they are the only reference to the object in the memory. These objects are rarely used but are useful when we want memory usage to be automatically managed. JavaScript WeakSet: It is used to store a collection of objects similar to that of set the only difference is that these values are only object and not some particular data type. Syntax: new WeakSet(object) Example: In this example, we will create a new WeakSet object and add elements to it using inbuilt methods.
Output: WeakSet {{…}, {…}}
WeakSet {} JavaScript WeakMap: In JavaScript, the WeakMap is used to store value in a key-value pair but it is different as the entries are weakly referred to. The key should always be a JavaScript object but the value can be any primitive JavaScript data type. Example: In this example, we will create a weakmap object and add elements to it.
Output: WeakMap {{…} => 'Raj', {…} => 'Rahul', {…} => 'Ram'} What to use? WeakMap is used to create a map-like structure so it is used when data is to be stored in key-value pairs and since it is a weak reference we only use it when data is to be automatically deleted from memory when it is the only reference remaining. We use WeakSet when we want to have unique values in our collection of objects. WeakSet is useful as it behaves like a set and like WeakMap it also has a weak reference.
|
Reffered: https://www.geeksforgeeks.org
JavaScript |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |