Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptWeakSet vs WeakMap in JavaScript

WeakSet vs WeakMap in JavaScript

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.

Javascript




var x = new WeakSet();
var y = new WeakSet(null);
x.add({});
x.add({});
console.log(x);
console.log(y);


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.

Javascript




function myGeeks() {
    var looseMap = new WeakMap();
    looseMap.set({}, "Ram");
    looseMap.set({}, "Raj");
    looseMap.set({}, "Rahul");
    console.log(looseMap);
}
myGeeks();


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.

WeakSet WeakMap
It is a collection of unique objects only It is a collection of key-value pairs
Map is two-dimensional Set is one-dimensional
Values can be accessed using keys Values can be accessed using inbuilt methods
Keys are strictly objects only and value can be primitive data type  It can take only objects as values and no other primitive data type
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments