Collision-resistant object keys
Attach metadata or internal state to an object without competing with ordinary string property names.
JavaScript · Class
Symbol is a built-in function that creates unique, immutable primitive values. Symbols can serve as non-colliding object property keys, while Symbol.for() provides shared values through the global symbol registry.
Symbol is a function-like built-in that creates an immutable primitive with unique identity. Use the resulting value as an object key when a property should not collide with string keys; use Symbol.for and Symbol.keyFor when sharing symbols through the global registry is required.
Symbol(description)| Name | Type | Description |
|---|---|---|
description | string | Optional text description associated with the symbol; it is used for display and does not determine uniqueness. |
A new primitive value of type symbol.
const secret = Symbol("secret");
const record = { id: 7, [secret]: "internal" };
console.log(record[secret]);
console.log(typeof secret);
console.log(Object.getOwnPropertySymbols(record).length);A symbol creates a unique property key that can be used and later retrieved through the same symbol reference.
Attach metadata or internal state to an object without competing with ordinary string property names.
Define protocol hooks recognized by JavaScript features, such as custom iteration behavior.
Share a named symbol between code that uses the global symbol registry.
Symbol() creates a unique primitive symbol, optionally carrying a description. Each call has distinct identity, even when descriptions match.
Follow-up: How can symbols be shared across realms? Use Symbol.for(key), which retrieves or creates a symbol in the global symbol registry.
A symbol can be used as an object property key, reducing accidental collisions with string-named properties. The same symbol reference is needed to access that property directly.
Follow-up: How can symbol-keyed properties be discovered? Object.getOwnPropertySymbols(object) returns an array of the object's own symbol keys.
Symbol is not constructible with new; attempting new Symbol() throws a TypeError. If an object wrapper is specifically needed, Object(symbol) creates one.
Follow-up: How can the primitive and wrapper be distinguished? typeof the primitive is "symbol", while typeof its wrapper is "object".
Symbol.for()Symbol.keyFor()Object.getOwnPropertySymbols()Symbol.prototype.descriptionSymbol.toPrimitive