![]() |
A WeakMap in JavaScript is a collection where keys can only be objects or non-registered symbols. It allows values of any type and doesn’t prevent the keys from being garbage collected, making its values eligible for garbage collection when their keys are collected. Syntaxnew WeakMap() Parameter: It has only one optional parameter.
Example 1: In this example The myGeeks function creates a WeakMap looseMap, sets objects as keys with names, assigns values, and checks if it has a specific key. Outputs the map and checks for presence of Ram.
Output: WeakMap {{…} => 'Raj', {…} => 'Rahul', {…} => 'Ram'} Example 2: In this example, we creates a WeakMap looseMap, sets an object Ram as a key with a value, nullifies Ram, and logs looseMap at different intervals.
Output: As the reference is removed from the memory so the value in looseMap are garbage collected WeakMap {{…} => 'Ram'} Supported Browsers:
We have a complete list of Javascript WeakMap methods, to check those please go through this JavaScript WeakMap Complete Reference article. JavaScript WeakMap – FAQsWhat is a WeakMap in JavaScript?
How do you create a WeakMap?
What are the main differences between Map and WeakMap?
How do you set and get values in a WeakMap?
Can you use primitive values as keys in a WeakMap?
How do you check if a WeakMap contains a specific key?
|
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |