JavaScript Symbols: Unique Keys, the Global Registry and Well-Known Symbols
What the symbol primitive is for: guaranteed-unique property keys that never clash, hidden from for...in and JSON, Symbol.for and the global registry, description, and the well-known symbols (iterator, toPrimitive, toStringTag, hasInstance, dispose) that let your objects plug into the language.
kvi5hnuCode Sprout team member6 min readOn this page
A symbol is a primitive value whose only job is to be unique. Every call to Symbol() creates a value that is not equal to any other value, ever. Symbols are mainly used as property keys that can't clash with anybody else's keys, and the language itself uses them as hooks: they're how you make an object work with for...of, customize how it converts to a number, or change what instanceof means.
Symbols arrived in ES2015 and are the least used primitive in everyday code. But you meet them constantly through iteration, and understanding them makes the more advanced parts of the language (iterators, generators, metaprogramming) much clearer.

Creating symbols
const id = Symbol("id");
const otherId = Symbol("id");
console.log(typeof id);
console.log(id === otherId); // same description, different symbols
console.log(id.description); // the label you gave it
console.log(id.toString()); // "Symbol(id)"
console.log(Symbol().description); // the label is optional
symbol
false
id
Symbol(id)
undefined
The string passed to Symbol() is only a description for debugging. It doesn't identify the symbol: two symbols with the same description are still different. Symbols have no literal syntax, and new Symbol() throws a TypeError (there are no symbol wrapper objects to create).
Symbols as property keys
Object property keys are normally strings. A symbol can be a key too, using bracket syntax:
const internalId = Symbol("internalId");
const user = {
name: "Ana",
[internalId]: 4071, // computed key in an object literal
};
console.log(user[internalId]); // read it with the symbol
console.log(Object.keys(user)); // string keys only
console.log(JSON.stringify(user)); // JSON ignores symbol keys
for (const key in user) console.log("for...in sees:", key);
console.log(Object.getOwnPropertySymbols(user)); // ask for symbols explicitly
console.log(Reflect.ownKeys(user)); // or for every key
4071
[ 'name' ]
{"name":"Ana"}
for...in sees: name
[ Symbol(internalId) ]
[ 'name', Symbol(internalId) ]
Why is this useful?
- No collisions. If two libraries both attach data to the same object under the string key
"id", one overwrites the other. With their own symbols, they can't interfere, because nobody else has the same symbol value. - Out of the way. Symbol-keyed properties don't show up in
for...in,Object.keys,Object.entriesorJSON.stringify, so they don't disturb code that iterates over or serializes the object.
But symbol keys are not private. Anyone can find them with Object.getOwnPropertySymbols or Reflect.ownKeys, and the spread operator and Object.assign copy them. For real privacy, use class private fields (#secret, part 9) or closures.
The global symbol registry
Sometimes you want different parts of a program, or different realms such as iframes and workers, to share one symbol. Symbol.for(key) looks the key up in a global registry, creating the symbol the first time:
const a = Symbol.for("app.cacheKey");
const b = Symbol.for("app.cacheKey"); // the same key returns the same symbol
console.log(a === b);
console.log(Symbol.keyFor(a)); // the registry key
console.log(Symbol.keyFor(Symbol("local"))); // not registered
true
app.cacheKey
undefined
Since the registry is global, choose namespaced keys like "myLibrary.featureName" to avoid accidentally sharing a symbol with unrelated code.
Symbols and conversion
Symbols refuse to be converted to strings or numbers implicitly, which prevents a symbol key from accidentally becoming the string "Symbol(id)":
const tag = Symbol("tag");
try { console.log("Tag: " + tag); } catch (err) { console.log("+ string:", err.name); }
try { console.log(`${tag}`); } catch (err) { console.log("template:", err.name); }
try { console.log(tag * 1); } catch (err) { console.log("number:", err.name); }
console.log(String(tag), tag.description); // explicit conversions work
console.log(Boolean(tag)); // every symbol is truthy
+ string: TypeError
template: TypeError
number: TypeError
Symbol(tag) tag
true
Well-known symbols: hooks into the language
The Symbol function has properties holding built-in symbols, called well-known symbols. The language looks for methods under these keys to decide how your objects behave. They were introduced as symbols precisely so that adding them couldn't break existing code that happened to use the same string names.
| Symbol | Lets an object customize | Covered in |
|---|---|---|
Symbol.iterator | for...of, spread, destructuring | part 12 |
Symbol.asyncIterator | for await...of | part 13 |
Symbol.toPrimitive | conversion to number or string | article 24 |
Symbol.toStringTag | the [object Name] from Object.prototype.toString | part 6 |
Symbol.hasInstance | the instanceof operator | part 9 |
Symbol.dispose, Symbol.asyncDispose | cleanup with using declarations (ES2027) | part 13 |
Symbol.species | which constructor derived arrays/promises use | part 9 |
Symbol.isConcatSpreadable | whether concat flattens the object | part 7 |
Symbol.match, matchAll, replace, search, split | how string methods treat the object as a pattern | part 11 |
Symbol.unscopables | names hidden from with | rarely needed |
Here are three of them in action:
class Countdown {
constructor(from) { this.from = from; }
*[Symbol.iterator]() { // makes the object iterable
for (let n = this.from; n > 0; n--) yield n;
}
get [Symbol.toStringTag]() { // customizes the type tag
return "Countdown";
}
}
const timer = new Countdown(3);
console.log([...timer]);
for (const n of timer) console.log("tick", n);
console.log(Object.prototype.toString.call(timer));
class Celsius {
constructor(degrees) { this.degrees = degrees; }
[Symbol.toPrimitive](hint) { // controls conversions
return hint === "number" ? this.degrees : `${this.degrees}°C`;
}
}
const today = new Celsius(21);
console.log(`${today}`, today * 2, today > 20);
[ 3, 2, 1 ]
tick 3
tick 2
tick 1
[object Countdown]
21°C 42 true
Other uses
- Unique constants. Instead of
const RED = "red",const RED = Symbol("red")gives a value nothing can accidentally equal, a lightweight enum. Remember that it won't surviveJSON.stringifyorstructuredClone. - Keys in Maps and WeakMaps. Symbols work as
Mapkeys, and since ES2023 non-registered symbols can also beWeakMapkeys andWeakReftargets. Registered ones (fromSymbol.for) can't, because they live forever. - Metadata on objects you don't own, such as tagging DOM nodes or objects from a library, without risking a name clash.
Common questions
Are symbols like private properties?
No. They're hidden from casual enumeration, not protected: Object.getOwnPropertySymbols(obj) lists them. Use #private class fields for true privacy.
Can symbols be sent through JSON, postMessage or structuredClone?
No. JSON.stringify skips symbol-keyed properties and omits properties whose value is a symbol (writing null inside arrays), and structuredClone throws a DataCloneError for a symbol value. Symbols exist only inside one running program.
What's the difference between Symbol("x") and Symbol.for("x")?
Symbol("x") always creates a brand-new symbol. Symbol.for("x") returns the one symbol registered under "x" in the global registry, creating it only on the first call, so every call with the same key returns the same symbol, even across iframes.
How do I get the text of a symbol?
sym.description (ES2019) returns the description string, or undefined if there was none. String(sym) and sym.toString() return "Symbol(description)".
Summary
Symbol(description)creates a unique primitive; the description is just a label.typeofgives"symbol".- Symbols make collision-free property keys, skipped by
for...in,Object.keysand JSON, but visible toObject.getOwnPropertySymbolsandReflect.ownKeys. They're not private. Symbol.for(key)shares one symbol through the global registry;Symbol.keyForreads its key.- Symbols can't be converted implicitly to strings or numbers; use
String(sym)orsym.description. - Well-known symbols such as
Symbol.iterator,Symbol.toPrimitive,Symbol.toStringTagandSymbol.disposelet your objects integrate with built-in language features.
Practice Questions
What does Symbol("a") === Symbol("a") return? And Symbol.for("a") === Symbol.for("a")?
Answer
false and true. Symbol() always makes a new value; Symbol.for returns the registered one.
An object has keys name (string) and a symbol key. What do Object.keys, JSON.stringify and { ...obj } do with the symbol key?
Answer
Object.keys omits it, JSON.stringify omits it, and the spread copies it.
Why does "key: " + Symbol("k") throw?
Answer
Symbols don't allow implicit conversion to strings, to avoid accidentally turning a symbol key into a string key. Use String(sym) or sym.description explicitly.
What method makes for (const x of myObject) work?
Answer
A method stored under the key Symbol.iterator that returns an iterator. Writing it as a generator, *[Symbol.iterator]() { ... }, is the simplest way.
Why did the language add new behavior through symbols like Symbol.iterator instead of a method named "iterator"?
Answer
Existing code might already have properties or methods named iterator, with unrelated meanings. A new, unique symbol can't collide with any existing string key, so adding the feature couldn't break old websites.
Previous: null and undefined in JavaScript: Differences, Checks and Best Practices
Next: The JavaScript Global Object and globalThis: Browsers, Node.js and Workers

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.