Logo with initials

Weak References in JavaScript

──── 2 mins

ES6 introduced WeakMaps and WeakSets, which brings weak and strong references to JavaScript, a concept front-enders are not particularly used to. If you’re working on games, you have to pay very close attention to how memory and performance is managed.

I’m using WeakMap here as an example, but it’s the same for WeakSet too. The main difference between Map and Set is that the latter only keeps unique values.

According to Wikipedia:

In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference.

That actually, surprisingly, makes a lot of sense! Wikipedia got me used to definitions like Coroutines are computer program components that generalize subroutines for non-preemptive multitasking by allowing execution to be suspended and resumed.

Alright, what a WeakMap does, compared to a good old Map or {} is each individual key element in the set can be garbage-collected when they are not referenced somewhere else:

If this is the content of a regular Map / {}:

const bigObject = {
  id: 'spritesheet-1',
  data: [
    /* gigantic array with a lot of stuff */
  description: 'hello bla bla',

And you’re only using it in the code like this

const spritesheetID = bigObject.id;
// the gigantic array in myMap.data is in memory

The whole object and the gigantic array will remain in memory and will not be CGed until it or its references are destroyed.

Whereas if you use a weak map anything that isn’t being used in your program will be garbage-collected.

// create a WeakMap from the big object
const weakMap = new WeakMap(Object.entries(bigObject));

// gigantic array is garbage-collected
const spritesheetID = weakMap.get('id');

Now you could manually delete the keys of the object that you don’t use, but this trick saves you having to keep track of your usage because this isn’t C++.

People have also found other ways to use this with promises and more in this Stackoverflow thread.

That’s all for this post, it’s a simple concept but needed clarification for me so I thought I might as well share it.

360 words