JavaScript Weak References Demystified

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 Weak References Demystified

Subscription Required

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

Fundamentals

let ref = { x: 10, y: 10 };
console.log(ref.x, ref.y); // 10 10

let weakRef = new WeakRef({ x: 10, y: 10 });
console.log(weakRef.deref().x, weakRef.deref().y); // 10 10

// After Garbage Collection
ref; // { x: 10, y: 10 }
weakRef.deref(); // undefined

console.log(ref.x, ref.y); // 10 10
console.log(weakRef.deref()?.x, weakRef.deref()?.y); // undefined undefined

Browser Demo

const createHeavy = () => ({ heavy: new Array(10_000_000).fill('🌹') });

let a = createHeavy(),
b = createHeavy(),
c = createHeavy();

let x = new WeakRef(createHeavy()),
y = new WeakRef(createHeavy()),
z = new WeakRef(createHeavy());

console.log('Strong', a.heavy[0], b.heavy[0], c.heavy[0]);
console.log('Weak', x.deref()?.heavy[0], y.deref()?.heavy[0], z.deref()?.heavy[0]);

a = null, b = null, c = null;
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

We've already looked at the JS Capabil, built in weak data structures, which are weak map and weak set. But if you want more low level control of weak references to build your own data structures or just want to gather a deeper understanding of how these data structures work underneath, then learning about the weak ref class is exactly what you need. Normally, when we assign an object to a variable, this is what JavaScript calls a strong reference, and since this is what we use most commonly, feel free to call it just a reference. We can use this reference to access the objects members. For example, the X and the Y properties.

00:33

Modern JavaScript comes with a built-in class called weak ref that takes an object into its constructor and then wraps it up into something that does not hold it using an assignment operator. What it does internally is actually more low level, and we do not have any special syntax for it. This is actually baked into the JavaScript runtime. Now, if you want to get access to the original object that the weak ref is wrapping, we actually have to use the D R F method provided on the weak reference. So as long as that original object has not been reclaimed by the garbage collector, we can access the X and Y, which should be 10 and 10. However,

01:10

if the garbage collector runs, for example, because of memory pressure and it wants to clear up as much memory as it wants, it might get rid of that original object that we passed to the B ref. However, any object that is truly referenced from our code, for example, by using the assignment operator will still exist. So REF will still have an object that has X and Y. However, we ref do DRE F might actually give us back undefined because the original object that we passed to V REF has been garbage collected. So unlike a reference where you can always use the properties that you want with

01:44

the V ref, you should always check if the response from D R F is undefined, for example, by using optional chaining. And that's pretty much all that there is to the weak ref. We have the weak ref constructor, which takes an object and the weak ref D a F method, which returns the object if it's still available or undefined if it has been garbage collected. As always, you could take my word for the fact that weak refs work, but seeing is believing and demoing a weak ref, letting go of its memory while a strong reference preventing garbage collection will give you some insight into how memory management works in JavaScript. Unlike our previous memory management tutorials, we,

02:20

we used special APIs within no js. Let's do the demo of the We Craft by using the Chrome Developer tools, and this will actually give you some insight in how you can profile and manage the performance of your own JavaScript applications. On the top, we have the performance tools with the memory checkbox selected, and at the bottom we have the developer console. Let's start recording to see what the memory profile of some code is going to look like. Within the console, we create this utility function called Create heavy, which creates an object which has a heavy property, which is going to be an array of 10 million items all filled with a rose

02:56

emoji. Next, we create three strong references To the objects that we create using this utility stored in variables A, B, and C. This should see our memory consumption go up because we've created some pretty heavy objects and this memory cannot be de allocated as long as A, B, C are pointing to those objects. Next, we create three more heavy objects, but this time we wrap them up with weak references. This means that while memory will be allocated, if there is ever memory pressure, then the garbage collector can jump in and free up the memory for these objects. The strong references A, B,

03:30

C will always contain the objects that point to those rose emojis. However, the weak re may or may not. Right now it seems that the garbage collector hasn't run, so the weak references do point to objects that contain the rose emoji. Now, let's push things in our favor a little bit by triggering the garbage collector manually by clicking the trashcan within Chrome developer tools. Since these objects were pretty large, the garbage collector has most likely reclaimed the memory for anything that was a weak reference, and our assumption is proved to be true. You can see the strong references still contain the rose emojis, however,

04:04

the weak references have all been played and they are now undefined. The garbage collector will be able to garbage collect the strong reference to objects as well if you were to assign A, B, and C to anything else like null values. So now if you're on the garbage collector again, we should be able to see a decrease in the memory consumption in the final profile that will be collected. And now for the moment of truth, the memory consumption actually looks exactly how we thought it would be. It starts off at a reasonable level, then it jumps up when we allocate those heavy objects and store them into strong references.

04:38

Then it jumps up again when we allocate more heavy objects and store them in weak references. But when we run the garbage collection, all of those weak reference to objects can actually get garbage collected and the memory consumption jumps down again. And finally, when we assign those strong references to null values, all of those can be garbage collected as well, and the memory consumption jumps down even further. As you mentioned in our lessons on other weak data structures, you really need to worry about weak references as objects and references that are used to hold their object normally live in the same scope and they get

05:12

garbage collected together. But it's great that JavaScript provides such low level control to its memory management while still keeping it high level enough that we aren't directly responsible for allocating and locating our own memory. 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