Creation of Weakmap
When we want to create a WeakMap, we have to use the WeakMap() constructor. This constructor will help us to create a new WeakMap object. We can add new key-value pairs, retrieve, check or remove existing ones.
// Create new WeakMap
const myWeakMap = new WeakMap()
Methods of Weakmap
By default, WeakMaps offer a variety of methods that make working with them easier. These methods allow us to perform all the important operations. These methods are get(), set(), delete() and has().
Let’s take a look at each.
Adding elements
To add a new key-value pair to WeakMaps, the set () method is what we need. This method takes two parameters.
- The first parameter is used for the key inside the key-value pair. This will be some object.
- The second parameter is for the value. This can be a number, string, boolean, etc.
One thing we need to remember about the set () method. This method allows us to add only one key-value pair at a time. If we want to add multiple pairs, we have to use this method multiple times, once for each pair.
Code Snippet:
// Create new WeakMap
const myWeakMap = new WeakMap()
//Let us Create some objects
const myObj1 = { name: 'Shubham' }
const myObj2 = { name: 'Afzal' }
const myObj3 = {}
// Add three new key-value pairs
myWeakMap. set (myObj1, 'I am quite sure about the guy.')
myWeakMap.set(myObj2, 'This is not a baller.')
myWeakMap. set (myObj3, 'We fired this guy earlier in this month')
Retrieving values
The get() method is used to get values from WeakMaps.
- This method takes one parameter, the object we used as a key, for the value we want to retrieve. If the key exists there, the get() method will return the associated value. Otherwise, it will return undefined to it.
Code Snippet:
// Let us Create WeakMap
const myWeakMap = new WeakMap()
// Create some objects
const myObj1 = { language: 'Java' }
const myObj2 = { language: 'Python' }
const myObj3 = { language: 'c++' }
// Add two new key-value pairs
myWeakMap.set(myObj1, 'Language for every platform-dependent, soon even a fridge.')
myWeakMap.set(myObj2, 'I miss those curly braces.')
// Retrieve the value associated with "myObj1"
myWeakMap.get(myObj1)
Output:
Language for every platform-dependent, soon even a fridge.
Removing elements
The best way to remove elements from WeakMaps is with the help of the delete() method.
- This method will take one parameter, a key. This is the object we used as the key to store the value associated with it. This method will return either false or true. True is returned if the pair in the WeakMap object has been removed successfully.
- If the pair was not removed, that means it will return false. We will also get false if the key does not exist in the WeakMap. The same will happen if we are trying to pass in a key that is not an object.
Code Snippet:
// Let us Create WeakMap
const myWeakMap = new WeakMap()
//Let us Create some objects
const myObj1 = { language: 'Java' }
const myObj2 = { language: 'Python' }
const myObj3 = {}
// Add two new key-value pairs
myWeakMap.set(myObj1, 'Semicolons or not good?')
myWeakMap.set(myObj2, 'White space matters a lot.')
// Remove the value associated with "myObj2"
myWeakMap.delete(myObj2)
Output:
true
Checking for existing keys
We know how to add values, retrieve them and remove them. The last thing we can do is to check if some key is present in a WeakMap. We can do this with the has() method.
- This method takes only one parameter, some object we want to know if it is used as a key or not. If the key exists, then the method will return true. Otherwise, it returns false.
Code Snippet:
// Create WeakMap
const myWeakMap = new WeakMap()
//Let us Create some objects
const myObj1 = { language: 'Java' }
const myObj2 = { language: 'R++' }
myWeakMap.set(myObj1, 'Not that dead yet still alive.')
myWeakMap.has(myObj1)
myWeakMap.has(myObj2)
Output:
true
true
false
Use Cases of WeakMaps
A scenario where WeakMaps will work very well is when we add some additional values to objects. If we try to do this with Maps, we will prevent those objects from being garbage collected. This will lead to worse performance and memory leaks. This is not a significant issue with WeakMaps because they don’t even prevent garbage collection.
If we add some object into a WeakMap, and we later remove all references to that object, garbage will be collected. There is also another significant benefit of using WeakMaps. WeakMaps are black boxes. We can't iterate over them to get the elements they hold. We also can't get their size.
This means we have to know which object we must use as a key to get a specific value. Otherwise, we will not get it. Another thing worth mentioning is that the lack of any clearing method. We can't remove all elements from WeakMap in a single go. We can remove them only one at a time and only if we know what key to use.
Differences between Maps and WeakMaps
Some of the essential differences are given below:
- The most significant difference between Maps and WeakMaps is the type of data we can use. In Maps, we can use any data type to create a key for the key-value pair. This also includes objects and functions. While weakMaps allow you to create keys only with objects and not with any other data type.
- Another critical difference is that all keys in a WeakMap are weakly referenced. Objects used as keys in a WeakMap can still be garbage collected. This will occur once all references to those items have been removed.
- WeakMaps are not iterable, which is the final significant distinction between Maps and WeakMaps. We can't iterate over them using a loop or forEach() method as we can over Maps.
These differences are pretty significant on what we can do with WeakMaps. However, don't let this discourage us from learning more about them because WeakMaps can still be more helpful.
For practice, you can try it on an online javascript editor.
Frequently Asked Questions
What is a WeakMap?
The WeakMap object is a collection of key/value pairs with weak references to the keys.
What is WeakSet?
WeakSet is a collection of objects only, and they cannot contain arbitrary values of any type, as sets can have arbitrary values.
Key takeaways
In this blog, we learned that WeakMaps are one of those lesser-known features of JavaScript. Indeed, they are not the best choice for storing data. However, there are jobs WeakMaps are a better fit for. For example, adding some additional metadata to objects. WeakMaps can do this exceptionally well.
I hope you learned what WeakMaps are, how they function, how they differ from Maps and other collections, and how to utilise them from this lesson.
You can use Coding Ninjas Studio to practise questions on web development and use the Coding Ninja Self-paced Web development to grasp numerous web development concepts.
Happy Learning!