Set Vs WeakSet in Javascript
JavaScript provides various data structures to manage collections of data, and two commonly used ones are Set and WeakSet. Both are used to store collections of values, but they have distinct characteristics and use cases. In this blog, we will explore the differences between Set and WeakSet with examples to help you understand when to use each one.
This post was originally posted at https://agrawalsuneet.github.io/blogs/set-vs-weak-set-in-javascript/ and later reposted on Medium.
Set
A Set is a built-in JavaScript data structure introduced in ECMAScript 6 (ES6) that allows you to store a collection of unique values. It can store any type of values, including primitive types and objects. Here’s an example of how to create and use a Set:
// Creating a Set
const mySet = new Set();
// Adding values to the Set
mySet.add(1);
mySet.add('Hello');
mySet.add({ name: 'John' });
// Checking the size of the Set
console.log(mySet.size); // Output: 3
// Checking if a value exists in the Set
console.log(mySet.has('Hello')); // Output: true
// Deleting a value from the Set
mySet.delete('Hello');
// Iterating through the Set
for (const item of mySet) {
console.log(item);
}
WeakSet
A WeakSet is also a collection of values, but it has a different purpose and behavior compared to Set. The primary difference is that a WeakSet can only store objects and does not prevent those objects from being garbage collected when they are no longer in use.