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.
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.
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);
}true false
Account { owner: 'ada' } {"owner":"ada"}
true false
TypeError: Invalid value used as weak map keysecrets.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.