Sub topic 5
What Can Be a Weak Target
This chapter assumes you know the difference between primitives and objects in JavaScript, that you have used Symbol(), and that you have read the earlier chapters on WeakRef and deref(). The examples need Node.js 20 or later, or a current browser.
The Rule Behind Every Weak API
A weak reference points at something the garbage collector can reclaim. That only makes sense for values that have an identity and a lifetime. The number 42 has neither: every 42 is the same value, and it can be recreated at any time. An object is different. Once the last strong reference to it is gone, nothing can produce that same object again.
The specification checks this with one internal operation, CanBeHeldWeakly. A value passes if it is:
- an object (this includes functions, arrays, class instances, and DOM nodes), or
- a symbol that is not in the global symbol registry, which means it was not created with
Symbol.for().
Every other value fails, and the API throws a TypeError.
Why Registered Symbols Are Excluded
Symbol.for('app.id') returns the same symbol every time any code calls it with that key, across the whole realm. You can always get it back, so it can never truly become unreachable. Allowing it as a weak target would produce a WeakRef that never clears, or a WeakMap entry that leaks forever. Plain Symbol('app.id') creates a new, unique symbol each time. Once you drop it, nobody can recreate it, so the collector can reclaim it.
function tryWeakRef(label, value) {
try {
new WeakRef(value);
console.log(`${label}: accepted`);
} catch (err) {
console.log(`${label}: ${err.constructor.name}`);
}
}
tryWeakRef('object', {});
tryWeakRef('function', () => {});
tryWeakRef('array', []);
tryWeakRef('unique symbol', Symbol('id'));
tryWeakRef('registered symbol', Symbol.for('id'));
tryWeakRef('string', 'hello');
tryWeakRef('number', 42);
tryWeakRef('null', null);
tryWeakRef('undefined', undefined);The first four lines print accepted and the rest print TypeError.
The Same Rule Everywhere
CanBeHeldWeakly controls every place where JavaScript holds something weakly:
| API position | Must pass `CanBeHeldWeakly`? |
|---|---|
| `new WeakRef(target)` | Yes |
| `WeakMap` key | Yes |
| `WeakSet` value | Yes |
| `FinalizationRegistry.register(target, ...)` target | Yes |
| Unregister token in `register()` / `unregister()` | Yes (the token is optional in `register()`) |
| Held value in `register()` | No, any value except the target itself |
| `WeakMap` value | No, any value |
The held value is the exception that matters. Strings and numbers make good held values, because they can be passed to the cleanup callback without keeping anything alive.
const registry = new FinalizationRegistry((key) => {
console.log(`collected ${key}`);
});
const target = {};
registry.register(target, 'user:17'); // fine: string held value
try {
registry.register(target, 'x', 'token'); // string token
} catch (err) {
console.log(err instanceof TypeError); // true
}A Common Mistake
Developers sometimes try to weakly cache by ID: new WeakRef(userId). That throws, because the ID is a primitive. Put the weak reference on the object the ID describes, and use the ID as the ordinary Map key or as the held value.
Exercise
Which of these calls throw a TypeError? (a) new WeakSet().add(Symbol('a')) (b) new WeakMap().set(Symbol.for('a'), 1) (c) new WeakRef(function () {}) (d) registry.register({}, Symbol.for('a'))
Show answer
Only (b) throws, because a registered symbol cannot be a WeakMap key. (a) is valid because unique symbols can be held weakly. (c) is valid because functions are objects. (d) is valid because a held value can be any value, including a registered symbol.
Exercise
Why can a symbol created with Symbol('x') be a WeakRef target while one created with Symbol.for('x') cannot?
Show answer
Symbol('x') is unique, and once every reference to it is gone no code can recreate it, so it can become unreachable. Symbol.for('x') lives in the global registry and can always be fetched again by its key, so it never becomes unreachable and a weak reference to it would be meaningless.