Sub topic 5
What Can Be a Weak Target
This chapter assumes you know how JavaScript objects and primitives differ, can create symbols with Symbol() and Symbol.for(), and have read the earlier chapters on WeakRef and deref(). It covers which values the engine will accept as the target of a weak reference, why it rejects the rest, and how to check a value before you use it.
The Rule: Only Values With Identity
A weak reference says: "Let me see this value as long as something else keeps it alive, and tell me when it is gone." That only makes sense if the value can actually be gone. It must have an identity: one specific instance that exists in memory and that can become unreachable.
The specification puts this check in one internal operation called CanBeHeldWeakly(v). It returns true in two cases:
vis an object. This includes functions, arrays, class instances, Promises, Proxies, DOM nodes, and boxed primitives such asnew String('x').vis a symbol that is not registered, meaning it was not created withSymbol.for().
Every other value fails the check. That covers undefined, null, booleans, numbers, bigints, strings, and registered symbols.
The same operation guards every weak API in the language. It decides what you can use as:
- a
WeakReftarget, - a
FinalizationRegistrytarget (the first argument toregister()), - a
FinalizationRegistryunregister token, - a
WeakMapkey, - a
WeakSetvalue.
Because the rule is shared, once you learn it for WeakRef you know it for all of them.
Why Primitives Are Rejected
Consider the number 42. You can write 42 anywhere in your program and get a value that is indistinguishable from every other 42. Nothing about it can become unreachable, because your code can always produce it again. Strings behave the same way: 'user-7' built by concatenation is equal to a literal 'user-7' in every observable sense.
If new WeakRef(42) were allowed, the engine would have two bad choices. It could never clear the reference, which makes it a strong reference under another name. Or it could clear it at some arbitrary moment, which would report the "death" of a value that still exists. The specification avoids both by throwing a TypeError.
const candidates = [
undefined,
null,
true,
42,
10n,
'hello',
Symbol.for('app.registered'),
];
for (const value of candidates) {
try {
new WeakRef(value);
console.log('accepted:', String(value));
} catch (err) {
console.log('rejected:', String(value), '->', err.constructor.name);
}
}Every line prints rejected: ... -> TypeError.
Why Registered Symbols Are Rejected
Symbols are primitives, but most of them have identity. Each call to Symbol('id') produces a new, unique symbol. If the last reference to it is dropped, no code can ever get it back, so the engine can safely collect it.
Registered symbols work differently. Symbol.for('app.key') looks up a global, cross-realm registry and returns the same symbol every time for the same string. Any code, at any time, can recreate it from the string alone. A registered symbol can never truly become unreachable, so it fails the check for the same reason strings do.
const unique = Symbol('session');
const registered = Symbol.for('session');
console.log(Symbol.keyFor(unique)); // undefined -> not registered
console.log(Symbol.keyFor(registered)); // 'session' -> registered
const ok = new WeakRef(unique);
console.log(ok.deref() === unique); // true
try {
new WeakRef(registered);
} catch (err) {
console.log(err instanceof TypeError); // true
}Symbol.keyFor() is how you tell the two apart at runtime. It returns the registry key for a registered symbol and undefined for any other symbol.
Well-known symbols
Well-known symbols such as Symbol.iterator and Symbol.asyncIterator are not in the Symbol.for() registry, so the specification accepts them as weak targets. They are never collected in practice, though, because the engine itself holds them for the life of the realm. A WeakRef to Symbol.iterator is legal and useless: deref() will always return the symbol, and a finalization callback for it will never run.
Summary Table
| Value | Example | Valid weak target? | Reason |
|---|---|---|---|
| Plain object | `{}` | Yes | Has identity |
| Function | `() => {}` | Yes | Functions are objects |
| Array | `[1, 2]` | Yes | Arrays are objects |
| Proxy | `new Proxy({}, {})` | Yes | The proxy is its own object |
| Boxed primitive | `new Number(5)` | Yes | The wrapper is an object |
| Unique symbol | `Symbol('x')` | Yes (ES2023+) | Cannot be recreated |
| Well-known symbol | `Symbol.iterator` | Yes, but never collected | Held by the realm |
| Registered symbol | `Symbol.for('x')` | No | Recreatable from its key |
| String, number, bigint, boolean | `'a'`, `1`, `1n`, `true` | No | No identity |
| `null`, `undefined` | `null` | No | No identity |
Checking a Value Before Use
There is no public canBeHeldWeakly function, but you can write one. The version below also detects whether the current engine supports symbol targets at all, so it gives the right answer on older runtimes.
const symbolTargetsSupported = (() => {
try {
new WeakRef(Symbol('probe'));
return true;
} catch {
return false;
}
})();
function canBeHeldWeakly(value) {
const type = typeof value;
if ((type === 'object' && value !== null) || type === 'function') {
return true;
}
if (type === 'symbol') {
return symbolTargetsSupported && Symbol.keyFor(value) === undefined;
}
return false;
}
console.log(canBeHeldWeakly({})); // true
console.log(canBeHeldWeakly(function () {})); // true
console.log(canBeHeldWeakly(Symbol('a'))); // true on ES2023+ engines
console.log(canBeHeldWeakly(Symbol.for('a'))); // false
console.log(canBeHeldWeakly('a')); // false
console.log(canBeHeldWeakly(null)); // falseThis check is useful in generic code, such as a cache or registry helper that accepts values from callers. It lets you fall back to a strong Map entry, or throw a clear error, instead of letting a TypeError from deep inside the engine reach the caller.
Targets, Tokens, and Held Values Follow Different Rules
FinalizationRegistry.prototype.register(target, heldValue, unregisterToken) takes three values, and each has its own rule:
targetmust passCanBeHeldWeakly. Otherwise it throws aTypeError.unregisterTokenmust passCanBeHeldWeaklyor beundefined. Otherwise it throws aTypeError.unregister(token)applies the same check and throws if the token cannot be held weakly.heldValuecan be any value, primitives included. Its only restriction is that it must not be the same value astarget. A later chapter covers held values in detail.
const registry = new FinalizationRegistry((held) => console.log('gone:', held));
const target = {};
registry.register(target, 'a string is fine here'); // OK
registry.register({}, 123, Symbol('token')); // OK on ES2023+ engines
try {
registry.register(target, 'x', 'string-token');
} catch (err) {
console.log('bad token:', err instanceof TypeError); // true
}
try {
registry.unregister(99);
} catch (err) {
console.log('bad unregister:', err instanceof TypeError); // true
}Edge Cases and Common Mistakes
Boxing a primitive does not make it weak
new WeakRef(new String('user-7')) is accepted, but the target is a new wrapper object that nothing else references. It can be collected right after the current job ends, and it has no relationship to other strings that read 'user-7'. If you want weak entries keyed by a string ID, keep the string as a strong Map key and make the value weak. The weak-value cache chapter builds exactly this.
A Proxy is not its target
A WeakRef to a proxy holds the proxy weakly. The proxy holds its target strongly. If you keep the original target alive elsewhere but drop the proxy, the proxy can be collected while the target survives. The reverse is also true: keeping the proxy alive keeps its target alive.
Unique symbols you leak stay alive
A unique symbol stored in a module-level constant, an exported binding, or a property of a long-lived object is strongly reachable. A WeakRef to it will never clear. Symbol targets are only useful when the symbol itself is passed around and eventually dropped, for example as a per-request or per-session handle.
Exercises
Exercise
Which of these calls throw a TypeError on an ES2023-compliant engine, and why? (a) new WeakRef(() => 1) (b) new WeakRef(Symbol.for('k')) (c) new WeakRef(Symbol('k')) (d) new WeakSet().add(0n)
Show answer
(b) and (d) throw. (b) is a registered symbol, and any code can recreate it with Symbol.for('k'), so it can never become unreachable. (d) is a bigint primitive, which has no identity. (a) is a function, and functions are objects. (c) is a unique, unregistered symbol. Both are accepted.
Exercise
A teammate writes registry.register(conn, conn.id, conn.id) where conn.id is a number. The call throws. Which argument is the problem, and how would you fix it so that explicit close() can still cancel the registration?
Show answer
The third argument, the unregister token, is the problem. Tokens must be objects or unregistered symbols, and a number is neither. The held value conn.id is fine because held values can be primitives. Use the connection object itself as the token: registry.register(conn, conn.id, conn), then call registry.unregister(conn) in close().
Exercise
Why does canBeHeldWeakly(Symbol.iterator) return true, and what happens if you register Symbol.iterator with a FinalizationRegistry?
Show answer
Symbol.iterator is a well-known symbol. It is not in the Symbol.for() registry, so Symbol.keyFor returns undefined and the check passes. The engine keeps well-known symbols alive for the life of the realm, so the registration succeeds but the cleanup callback will never run.