Skip to content
jshacks.dev
Fundamentals

Use a WeakMap for private data

Keep private data for an object in a WeakMap so it never shows in the object, in JSON or in the console, and see the TypeError for a non-object key. Node.js 18.

2 min read
Summarize in AI

Data that must stay attached to an object but invisible, such as a pin, a handle or a cached result, can live in a WeakMap keyed by the object itself. Node.js 18 and later behave as the output shows.

JavaScript
const secrets = new WeakMap();

class Account {
  constructor(owner, pin) {
    this.owner = owner;
    secrets.set(this, { pin });
  }
  check(pin) {
    return secrets.get(this).pin === pin;
  }
}

const account = new Account('ada', '1234');
console.log(account.check('1234'), account.check('0000'));
console.log(account, JSON.stringify(account));
console.log(secrets.has(account), secrets.has({ owner: 'ada' }));

try {
  secrets.set('ada', 1);
} catch (error) {
  console.log(error.name + ': ' + error.message);
}
Text
true false
Account { owner: 'ada' } {"owner":"ada"}
true false
TypeError: Invalid value used as weak map key

secrets.set(this, { pin }) stores the value outside the object. The account prints as Account { owner: 'ada' } and serializes as {"owner":"ada"}, so the pin cannot leak through a log line or a response. Only code that can reach the secrets map can read it. When the account is garbage collected the entry goes with it, which is the difference from a regular Map, and the reason keys must be objects: secrets.set('ada', 1) throws TypeError: Invalid value used as weak map key. The collection is defined in the specification for WeakMap objects.

For your own classes, a private field such as #pin is simpler, and it is the better choice. A WeakMap earns its place when you do not own the class, for instance when you attach data to a DOM node, a request object or an instance from a library. A WeakMap cannot be iterated or counted.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.