A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-weakset/ below:

JavaScript WeakSet - GeeksforGeeks

JavaScript WeakSet

Last Updated : 11 Jul, 2025

A WeakSet in JavaScript is a collection of unique objects where the values are weakly referenced. It works similarly to a Set, but the objects stored in a WeakSet can be garbage-collected when no longer in use.

Syntax

const weakSet=new WeakSet()

The syntax const weakSet = new WeakSet(); initializes a new empty WeakSet in JavaScript. It creates a collection that can only store objects and automatically removes objects when they are no longer in use.

How a Weak Set Works Components of a Weak Set Implementation of Weak Set

This code demonstrates how to use a WeakSet in JavaScript to store and manage unique objects. It shows adding, checking, and removing objects, as well as how objects can be garbage collected when no longer referenced.

JavaScript
// Create a new WeakSet
let weakSet = new WeakSet();

// Create objects to use in the WeakSet
let obj1 = { name: "Pranjal" };
let obj2 = { name: "Pranav" };
weakSet.add(obj1);
weakSet.add(obj2);
weakSet.delete(obj1)
obj2=null
console.log(weakSet.has(obj1))
console.log(weakSet.has(obj2))
Functions present in Weak Set Coding Problems on Weak Set Advantages of Weak Set Conclusion

In conclusion, a WeakSet in JavaScript is a powerful tool for managing collections of unique objects with automatic memory management. By allowing objects to be garbage collected when no longer referenced, it helps prevent memory leaks and ensures efficient resource usage. Though limited in features like iteration, its unique properties make it ideal for specific use cases such as storing private data and improving memory efficiency.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4