JavaScript Symbol Values and Unique Keys
Quick answer
A Symbol is a primitive value whose identity can be distinct even when its description matches another symbol. Symbols are useful as property keys when a plain text name might collide with another key.
How it works
Call Symbol(description) to create a fresh symbol. The description is a label for debugging, not its identity. Symbol.for(key) instead retrieves or creates a symbol in the global symbol registry. A property key can be a string or a symbol; bracket access with a symbol uses its identity. The object literal and property access below preview a later chapter.
console.log(Symbol("id") === Symbol("id"));console.log(Symbol.for("id") === Symbol.for("id"));Expected output in Node.js:
falsetrueFresh symbols differ; the registry reuses one key.
const key = Symbol("id");const record = { id: 7 };record[key] = 9;console.log(record.id);console.log(record[key]);Expected output in Node.js:
79The string id and symbol key occupy different properties.
Common mistakes
Symbol properties are not secret or private. Reflection can discover them. A symbol description does not make two fresh symbols equal. Do not return raw symbols from JSON-based exercises.
Practice
Predict both comparisons, then use a different registry key and compare the symbols again. Explain why the fresh-symbol comparison remains false.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Symbol Values and Unique Keys — Knowledge Check
Apply the taught concept and reason about the result.
What is Symbol("key") === Symbol("key")?
What is Symbol.for("topic") === Symbol.for("topic")?
What is the purpose of a symbol description?
Which property access uses a symbol key stored in key?
Are symbol-keyed ordinary properties guaranteed private?