
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why We Need WeakMaps in JavaScript
WeakMap is a collection in JavaScript. This type of collection is used to store the data in the form of key-value pairs. In WeakMap, the key must definitely be an object and the values can be of any type.
The difference between a Map and a WeakMap is, in weakmap key must be an object and the other difference is that a weakmap is like a blackbox where the keys can't be retrieved.
The value of the weakmap can be accessed only if the key is known which means the values in the weakmap are private.
Additional data can be stored in a weakmap which is related to any object without changing the data in it and it also manages its memory too.
Need for the Weakmaps
Using WeakMaps we can achieve the following ?
Storing the data of a class which is private
The private data of classes and the objects can be stored in weakmaps, as they are also called as black boxes. As there are many other ways in which storing of private data can be done, this is rarely used.
Example
// using object let wm = new WeakMap();// weakmap let student = {},//object student2 = {}; // set the data into weakmap wm.set(student, " private data"); wm.set(student2, "Private data 2"); // get the data from weakmap console.log(wm.get(student)); console.log(wm.get(student2)); // using class class studentdata { constructor() { wm.set(this, "private"); } printPrivate() { console.log(wm.get(this)); } } let s = new studentdata(); s.printPrivate();
Keeping track of DOM changes
Google Polymer Project is a library which provides some features to create custom elements and these features makes the customization easy and fast. So, this project uses the weakmaps to save the changes of DOM elements. Additional information of the DOM elements can also be stored.
In Caching
If array of elements is given as input and the sum of all the elements is calculated. Here, as the array is also an object it can also be stored as a key in the weakmap.
An important point to be remembered while in the case of weakmaps is that, if there is a scenario of keeping track of the additional information relating to the behaviour of the object, when
That no modification or addition of other properties should be done and
No special care is taken while memory management,
Then it is a scenario where the Weakmaps can be used without hesitation and a second thought.