Horje
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.

WeakSetWeakMap
It is a collection of unique objects onlyIt is a collection of key-value pairs
Set is one-dimensionalMap is two-dimensional
Values can be accessed using keysValues 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



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to display images from an array in JavaScript ? How to display images from an array in JavaScript ?
Next.js getInitialProps Next.js getInitialProps
JavaScript Date setYear() Method JavaScript Date setYear() Method
JavaScript Array findLastIndex() Method JavaScript Array findLastIndex() Method
Next.js Disabling ETag Generation Next.js Disabling ETag Generation

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12