in JavaScript by
Q:
Explain WeakSet in javascript.

1 Answer

0 votes
by
In javascript, Set is a collection of unique and ordered elements.

Just like Set, WeakSet is also a collection of unique and ordered elements with some key differences:

Weakset contains only objects and no other type.

An object inside the weakset is referenced weakly. This means, if the object inside the weakset does not have a reference, it will be garbage collected.

Unlike Set, WeakSet only has three methods, add() , delete() and has() .

const newSet = new Set([4, 5, 6, 7]);

console.log(newSet);// Outputs Set {4,5,6,7}

const newSet2 = new WeakSet([3, 4, 5]); //Throws an error

let obj1 = {message:"Hello world"};

const newSet3 = new WeakSet([obj1]);

console.log(newSet3.has(obj1)); // true
Click here to read more about JavaScript
Click here to read more about Insurance

Related questions

0 votes
asked Dec 10, 2020 in JavaScript by SakshiSharma
0 votes
asked Dec 10, 2020 in JavaScript by SakshiSharma
0 votes
asked Aug 24, 2020 in JavaScript by Hodge
0 votes
asked Feb 6, 2020 in JavaScript by rajeshsharma
0 votes
asked Feb 6, 2020 in JavaScript by rajeshsharma
...