DEV Community

Cover image for JavaScript Use Cases of WeakMap
Bello Osagie
Bello Osagie

Posted on • Edited on

1

JavaScript Use Cases of WeakMap

In the previous article, we learned that once the keyed object in WeakMap is changed/overridden to null, it gets removed from memory because the WeakMap can't reach it any longer. It helps to free up space when past stored data are not needed. Such objects are garbage-collected automatically. JavaScript engine cleans up the memory at a specific instance.

let bello = { name: "Bello" };

const weakMap = new WeakMap();
weakMap.set(bello, 'secret documents');

bello = null; // changed/overriden reference

console.log( weakMap.has(bello) ); // false 
// bello is removed from memory!
Enter fullscreen mode Exit fullscreen mode

If Map is used in place of weakMap then the object bello still exists provided WeakMap is alive even though it can't get the reference to its keyed object, bello. Such objects are non-garbage-collected.

let bello = { name: "Bello" };

const map = new Map();
map.set(bello, 'secret documents');

bello = null; // overwrite the reference

console.log( map.keys() ); // [Map Iterator] { { name: 'Bello' } }
// bello still exist
Enter fullscreen mode Exit fullscreen mode

Let's see the use cases of WeakMap below:


Additional data storage

In the example above, if bello dies then the secret documents will be destroyed automatically.

Another example is to assume a website is accessible to signed-up users.

In the example below, the user object is the key and the signed-up count is the value.

signup.js

const signedUpMap = new WeakMap(); // weakmap: user => visits count

// increase the visits count
function countUser(user) {
  let count = signedUpMap.get(user) || 0;
  signedUpMap.set(user, count + 1);
}
Enter fullscreen mode Exit fullscreen mode

For a user that deletes his/her account, the count is reduced and the data of the user are removed from memory automatically.

count.js

let bello = { name: "Bello" };

countUser(bello); // bello signed-up

bello = null; // Bello deleted his account
Enter fullscreen mode Exit fullscreen mode

Caching

Cache memory is a chip-based computer component that makes retrieving data from the computer's memory more efficient. It acts as a temporary storage area for the computer's processor to retrieve data from easily - SeachStorage

Let's assume we can store (cache) results from a function, so that future calls on the same object can reuse it.

cache.js

let cache = new WeakMap();

// calculate and remember the result
function process(obj) {
  if (!cache.has(obj)) {
    let result = /* calculate the result for */ obj;

    cache.set(obj, result);
  }

  return cache.get(obj);
}
Enter fullscreen mode Exit fullscreen mode

main.js

let obj = {/* some object */};

let result1 = process(obj);
let result2 = process(obj);

// ...later, when the object is not needed any more:
obj = null;

// Can't get cache.size, as it's a WeakMap,
// but it's 0 or soon be 0
// When obj gets garbage collected, cached data will be removed as well
Enter fullscreen mode Exit fullscreen mode

For multiple calls of process(obj) with the same object, there's a clean-up of cache when certain objects are not needed. That is, the cached result will be removed from memory automatically after the object gets garbage collected.

You can read more on cache on MDN


Buy me a Coffee


Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay