Exploring the WeakMap Feature in JS - Part 1

By Sammy at

In JavaScript, objects can be used to store and retrieve data using keys. However, there are some cases where you may want to associate data with an object, without modifying the object itself. This is where WeakMaps come in.

A WeakMap is a special type of map in JavaScript that allows you to associate data with an object, without modifying the object's own properties. In a WeakMap, the keys are weakly held, which means that they don't prevent the garbage collector from cleaning them up when they are no longer needed.

Here's an example of how a WeakMap can be used to store private data associated with an object:

const privateData = new WeakMap();

class MyClass {
  constructor() {
    privateData.set(this, {
      value: 42
    });
  }

  getPrivateValue() {
    return privateData.get(this).value;
  }
}

const myObject = new MyClass();
console.log(myObject.getPrivateValue()); // Output: 42

In this example, privateData is a WeakMap that stores private data associated with an instance of MyClass. The data is stored using the set method of the WeakMap, with the instance of MyClass as the key, and an object containing the private data as the value.

The getPrivateValue method retrieves the private data associated with the instance of MyClass using the WeakMap, and returns the value property of the object.

Using a WeakMap to store private data ensures that the data is not accessible from outside the instance of MyClass. The data is also automatically cleaned up by the garbage collector if the instance of MyClass is no longer needed.