cover-img

WeakMap and WeakSet

20 January, 2023

3

3

0

What is WeakMap JavaScript?

A WeakMap in JavaScript is a collection of key/value pairs in which the keys are weakly referenced. This means that the keys are held weakly and can be garbage collected if no other strong references exist. This contrasts with a regular Map, where the keys are strongly referenced and will only be garbage collected once removed.

Developers generally prefer using WeakMaps for cases where the keys are temporary and should be garbage collected when they are no longer needed.

Here is an example of how to use a WeakMap in JavaScript:

// create a new WeakMap
const map = new WeakMap();

// create an object to use as a key
const key = {};

// add a value to the WeakMap using the object as the key
map.set(key, "value");

// get the value from the WeakMap using the object as the key
console.log(map.get(key)); // prints "value"

// remove the object from memory
key = null;

// the key object is now eligible for garbage collection

Note: WeakMap does not have the size property, you can't iterate over it, and it does not have a clear method.

Also, you can not use a primitive type as a key on WeakMap.

What is WeakSet in Javascript?

Similar to WeakMap, a WeakSet in JavaScript is a Set-like collection of objects in which the objects are weakly referenced.

Here is an example of how to use a WeakSet in JavaScript:

// create a new WeakSet
const set = new WeakSet();

// create an object to add to the WeakSet
const object1 = {};
const object2 = {};

// add the object to the WeakSet
set.add(object1);
set.add(object2);

// check if an object is in the WeakSet
console.log(set.has(object1)); // prints true

// remove the object from memory
object1 = null;

// the object is now eligible for garbage collection

WeakSet also does not have the size property, you can't iterate over it, and it does not have a clear method.

3

3

0

ShowwcaseHQ
Showwcase is where developers hang out and find new opportunities together as a community

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.