Collision-resistant object keys
Adding metadata or internal fields to objects without colliding with ordinary string property names.
JS Puzzles · Const
JavaScript symbols are primitive unique identifiers. Separate Symbol() calls stay distinct even with the same description, while Symbol.for(key) reuses a symbol from the global registry.
Calling Symbol() creates a primitive identifier that remains distinct from every other symbol, even when descriptions match. The description is only a label. If code needs the same symbol to be retrieved repeatedly by name, use Symbol.for(), which consults the global symbol registry and creates an entry when needed.
Symbol(description)
Symbol.for(key)| Name | Type | Description |
|---|---|---|
description / key | string | An optional description or registry key used to label or retrieve a symbol. |
Symbol() returns a unique primitive symbol; Symbol.for(key) returns the registry symbol associated with key, creating it if absent.
const first = Symbol("id");
const second = Symbol("id");
console.log(first === second); // false
console.log(Symbol.for("shared") === Symbol.for("shared")); // trueSeparate Symbol() calls remain distinct, while Symbol.for() reuses a registry entry for the same key.
Adding metadata or internal fields to objects without colliding with ordinary string property names.
Sharing one named symbol between modules or other code that uses the same registry key.
Representing internal identifiers whose identity should not be recreated accidentally.
Each Symbol() call produces a distinct primitive, so Symbol("x") === Symbol("x") is false. The optional description does not participate in symbol identity.
Follow-up: How can separate parts of an application obtain the same symbol? Use Symbol.for("x"), which retrieves or creates the registry entry for that key.
Symbol.for(key) checks the global symbol registry and returns the existing entry for that key, creating one if necessary. Repeated calls with the same key therefore return the same symbol.
Follow-up: What is the contrasting behavior of Symbol("x")? It creates a fresh symbol on every call, even when the description is identical.
A symbol is a primitive value used as a unique identifier, and it can serve as an object property key. This allows code to add a property without accidentally colliding with an unrelated string-named property.
Follow-up: What should be used for cross-code shared identity? A registered symbol from Symbol.for(), accepting that its identity is intentionally shared rather than fresh.
Symbol()Symbol.for(key)global symbol registryunique identifierobject property key