JavaScript WeakSet Explained with Examples

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript WeakSet Explained with Examples

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Fundamentals

let a = { element: 'div' };
let b = { element: 'input' };

let set = new Set();
set.add(a);
set.add(b);

console.log(set.has(a)); // true
console.log(set.has(b)); // true

// a and b go out of scope
a = null;
b = null;

// Set => has an internal strong reference to its members
console.log([...set]); // [ { element: 'div' }, { element: 'input' } ]
// so the original objects are not garbage collected

let x = { element: 'div' };
let y = { element: 'input' };

let weakSet = new WeakSet();
weakSet.add(x);
weakSet.add(y);

console.log(weakSet.has(x)); // true
console.log(weakSet.has(y)); // true

// x and y go out of scope
x = null;
y = null;

// WeakSet => has an internal weak reference to its members
// allows garbage collection of the original x and y objects

WeakSet API

const alpha = { name: 'autobot' };
const omega = { name: 'decepticon' };

const weakSet = new WeakSet([alpha]);
weakSet.add(omega);

console.log(weakSet.has(omega)); // true
console.log(weakSet.delete(omega)); // true
console.log(weakSet.has(omega)); // false
console.log(weakSet.delete(omega)); // false

// [...weakSet] // TypeError: weakSet is not iterable
// size
// clear()

Garbage Collection Demo

Note: uses utilities memoryUsed, collectGarbage we built in our previous lesson.

function fill(setLike, char) {
const objects = [...Array(2500)]
.map(_ => ({ id: new Array(100_000).fill(char) }));
for (const object of objects) {
setLike.add(object);
}
}

console.log('-------------- Set --------------');
let set = new Set();
console.log('Start', memoryUsed());
fill(set, '😢');
console.log('After', memoryUsed());
collectGarbage();

console.log('----------- DeScope Set ---------');
set = null;
collectGarbage();

console.log('------------- WeakSet -----------');
const weakSet = new WeakSet();
console.log('Start', memoryUsed());
fill(weakSet, '🤗');
console.log('After', memoryUsed());
collectGarbage();

Use Case Example

const visited = new WeakSet();
function hasVisited(object) {
return visited.has(object);
}
function visit(object) {
visited.add(object);
}

let john = { name: 'John' };
let mary = { name: 'Mary' };
let jack = { name: 'Jack' };

visit(john);
visit(mary);

console.log(hasVisited(john)); // true
console.log(hasVisited(mary)); // true
console.log(hasVisited(jack)); // false

john = null;
mary = null;
jack = null;

// objects previously referenced by john, mary, jack can be garbage collected
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

The weak set, which is built into JavaScript offers the same feature of weak referencing its members as we previously saw for the built-in weak map data structure. And for this specific use case of a not blocking garbage collection, it's a drop-in replacement. For the built-in set. Consider two simple objects contained within variables A and B. We can create a set within JavaScript using the set constructor and add these objects to that set. Having these objects within the set allows us to know very quickly if these objects are present within the set or not. By using the set dot has function, the set TE structure holds a strong reference to the elements that it contains,

00:37

just like the assignment operator, which means that as long as the set is within scope, those objects cannot be garbage collected. So even if we assign A and B to null, we would hope that the memory allocated for those objects is available for garbage collection. It'll not be possible because the set has an internal strong reference and we can actually prove that the set has that reference by simply iterating over the set. And there we go. We have those original objects. This is the main difference between the set and the weak set. The weak set does not hold a strong reference to its members,

01:12

so let's just create two new variables, X and Y pointing to two different objects. And just like the set, we can create a weak set by using the weak set constructor and this allows us to add these objects to the weak set and the weak set does have the has method that tells us very quickly if an object does or doesn't exist within the weak set. However, unlike the strong reference assignment operator, weak set internally uses something molo level, which is called a weak reference that allows the original object to be garbage collected. So if the original objects go out of scope, for example,

01:46

we assign X and Y to null because the weak set only has an internal weak reference to its members, it allows the garbage collection of those original X and Y objects. And a simple proof of the fact that a weak set only has a weak reference is that it doesn't allow us in any shape or form to find out what items exist within it. Unlike the set, the weak set is not it. The weak set shares the same restrictions as the weak map that is its items, it must be objects and the weak set itself is not attri. Beyond that, the weak set has the same A P I as the set data structure,

02:22

the restriction that members must be objects is there because the members of the weak set must be something that the garbage collector can collect. Here we have two simple objects to demonstrate the a p I of the weak set and just like the set, the weak set also accepts an interval in the constructor. So here we are creating a weak set that only has one item, which is the alpha object. Also, just like the set, we can add items using the ad method, we can check if an item exists. Using the haz method, we can remove an item from the set by using the delete method. And of course, once this item is removed, has will return false. Also, just like the set,

02:56

the weak set delete will return to if The item did exist and it'll return false if the item that we try to remove did not previously exist within the set. All of this a p i is actually shared between the weak set and the set classes, but that's where the similarities end. Unlike the set, the weak set is not a triple and if we actually try to iterate over it, c JavaScript will throw a type error. Similarly, it does not have the size property because it doesn't keep a strong track of the objects that it contains and it doesn't have the clay method because there is nothing too clear.

03:30

We cannot find out anything about the weak set unless we have the original objects. You can take my word for the fact that weak sets work, but if you are like me and feel that seeing is believing and strap right in and let's demonstrate that a set blocks garbage collection and a weak set doesn't, we create a simple fill function that takes a set like data structure and a character and then creates an array of objects. 2,500 strong where each object has an ID property, which is an array filled with that character a hundred thousand times.

04:04

Now all of these objects are only going to exist within the scope of this function, so when this function returns, they should all be available for garbage collection. However, before we return, we add all of these objects to the set like data structure that gets passed in. Let's conduct a simple test to compare the memory characteristics of the set in the weak set classes. And for this, we will use the utilities we built in our lesson on JavaScript memory management and garbage collection. First up, let's see how the set performs. We create a set and start off by noting down the current amount of memory being

04:39

used. We fill that set up with the crying emoji and afterwards a note on the memory used and then invoke the garbage collector to see if we can free up any memory. The expectation here is that all of those objects created within the fill function are still within scope because the set is holding onto a strong reference to those objects and we can actually prove it even further by simply getting rid of the set. If we assign set to null and then try to collect the garbage, then hopefully we should be able to see that memory getting reclaimed. Now let's try the same process with the weak set.

05:12

We create an instance of the weak set. We log out the current memory being used, fill that weak, set up with the hugging emoji and then log out the memory being used afterwards and then try to collect the garbage to see if we can reclaim any of that memory. Hopefully, since the weak set doesn't have a strong reference to its members, all of those objects created within fill should get garbage collected. And now for the moment of truth, you can see that with the set we start off with 50 mb, but then it jumps up by a thousand. And even though we try to run the garbage collector,

05:44

we are not able to free up any of that memory. However, when we assign the set to null and run the garbage collector again, no surprise, all that memory gets freed up so it was being blocked by the set. Next with the weak set, all of those objects do get stored within it and the memory does jump up, but then when we collect the garbage, because those objects are no longer within scope, all of that memory gets freed up. An obvious question you should have is what are the main use cases for using the weak set? The answer is pretty simple. Use a weak set whenever you want to track if you've seen an object before,

06:19

but do so without holding a strong reference to the object, so the object can be garbage collected if required. To demonstrate set a use case, we create a simple weak set called visited with nice utility methods called has visited, which takes an object and sees if it is present within the set and a visit utility, which takes an object and adds it to the visited week set. The intent here is that these utilities can exist in a library or a framework that is going to be independent of the scope and the lifecycle of the objects that we are dealing with. Let's just create a few simple objects, John, Mary,

06:53

and Jack. And then John comes to visit and then Mary comes to visit. And at this point we can see that John came to visit, Mary came to visit, and Jack didn't come to visit. Now even though this information is coming from the weak set, the weak set is not blocking the lifecycle of these objects. So if John, Mary and Jack all get freed up, the objects previously referenced by these variables can now be garbage collected. Weak set is probably not something that you'll be using often as the objects you are dealing with will most likely live in the same scope as your set data structure.

07:26

So you don't need to worry about holding a strong reference as they will both get garbage collected together. That said, weak set can come in handy when you are building advanced frameworks and if you ever run across the weak set in a code base, you can now be confident that it is something that you already know. As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36