Subverting control with weak references

02-Mar-2025 56
In JavaScript we have two APIs to work with weak references: WeakMap and WeakRef. (Before I wrote this article I thought WeakRef was only a proposal, but it turns out most browsers have already implemented it) One of the more common use cases uses WeakMap. This data structure keeps a weak reference to the keys in the map, and a strong reference between the keys and values. I guess I should explain what a "weak reference" is: usually if you have a reference to an object in a variable, it stops the garbage collector from deleting it (which makes sense). It'd be weird if suddenly your variable pointed to nothing right?.
Use coupon code:

JAVASCRIPT

to get 40% discount on our 'The JavaScript Interview Bible' book!
Prepare for your next tech interview with our comprehensive collection of programming interview guides. Covering JavaScript, Ruby on Rails, React, and Python, these highly-rated books offer thousands of essential questions and answers to boost your interview success. Buy our 'Ultimate Job Interview Preparation eBook Bundle' featuring 2200+ questions across multiple languages. Ultimate Job Interview Preparation eBook Bundle