Symbols & Well-Known Symbols
Published by Brayan K
A Symbol is a unique, primitive value created with Symbol() that serves as a collision-proof object key and lets you hook into built-in language behaviors through well-known symbols like Symbol.iterator.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A description labels a symbol; it does not identify it
Use a symbol when two independently created keys must remain distinct even if their human-readable labels match. The identity is the symbol value itself. A description is useful for inspection, but reconstructing a symbol from that description creates a different key.
// A description helps humans; identity comes from the returned value.
const first = Symbol("status");
const second = Symbol("status");
const record = { [first]: "ready", [second]: "waiting" };
console.log(first === second);
console.log(first.description, second.description);
console.log(record[first], record[second]);
console.log(record[Symbol("status")]);
// ✅ Expected output:
// false
// status status
// ready waiting
// undefinedComputed property syntax uses the symbol value as the key. A literal property named first would instead be the string "first". Symbols are primitives; calling Symbol is supported, constructing it with new is not.
new Symbol("status");
// ✅ Expected error:
// TypeError: Symbol is not a constructorconst token = Symbol("entry");
console.log(String(token));
console.log(token.description);
try { console.log("token: " + token); }
catch (error) { console.log(error.name); }
// ✅ Expected output:
// Symbol(entry)
// entry
// TypeErrorString(symbol) is an intentional display conversion. Concatenation attempts an implicit conversion and throws. A description may be undefined, and it is not necessarily unique or suitable for a persistent identifier.
Registered symbols deliberately share identity
const first = Symbol.for("lesson.status");
const second = Symbol.for("lesson.status");
const local = Symbol("lesson.status");
console.log(first === second, first === local);
console.log(Symbol.keyFor(first));
console.log(Symbol.keyFor(local));
console.log(Symbol.iterator === Symbol.for("Symbol.iterator"));
// ✅ Expected output:
// true false
// lesson.status
// undefined
// falseSymbol.for uses the global symbol registry for its string key. This is useful when independently written code deliberately agrees on a shared key; it also means a second caller who knows the registry string can retrieve that symbol. Symbol.keyFor returns the registry key for a registered symbol, not every symbol’s description. Well-known symbols such as Symbol.iterator are their own language-defined values.
Do not use a registered symbol as a secret. Nor can you serialize a fresh symbol’s identity as its description and expect a later Symbol call to restore it. If data must cross JSON or a process boundary, choose an explicit string identifier and a validation contract.
A symbol field is discoverable even when Object.keys omits it
const token = Symbol("note");
const record = { visible: 1, [token]: "readable" };
console.log(JSON.stringify(Object.keys(record)));
const found = Object.getOwnPropertySymbols(record);
console.log(found.length, record[found[0]]);
console.log(Reflect.ownKeys(record).map(String).join(", "));
console.log(Object.assign({}, record)[token]);
console.log(({ ...record })[token]);
console.log(JSON.stringify(record));
// ✅ Expected output:
// ["visible"]
// 1 readable
// visible, Symbol(note)
// readable
// readable
// {"visible":1}Object.keys and JSON serialization omit symbol-keyed fields. Reflection can discover the symbol keys, and assign/spread copy enumerable symbol fields. “Not in a common enumeration” is different from “inaccessible.” Object Methods (keys, entries, assign, freeze) owns the complete own/enumerable property matrix; Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns trust boundaries.
const token = Symbol("entry");
console.log(JSON.stringify({ value: token }));
console.log(JSON.stringify([token]));
console.log(JSON.stringify(token) === undefined);
// ✅ Expected output:
// {}
// [null]
// truetry { structuredClone({ value: Symbol("entry") }); }
catch (error) { console.log(error.name); }
// ✅ Expected output:
// DataCloneErrorThe JSON results follow JSON’s representation rules, not a reversible symbol encoding. A symbol used as a value also cannot be carried through structuredClone. Deep Dive into JSON, Parsing & Serialization owns serialization choices; Deep Copy vs Shallow Copy & Data Structures owns clone behavior.
Well-known symbols are protocol hooks with specific contracts
const quantity = {
[Symbol.toPrimitive](hint) {
console.log("hint", hint);
return hint === "string" ? "nine units" : 9;
}
};
console.log(String(quantity));
console.log(Number(quantity));
console.log(quantity + 1);
// ✅ Expected output:
// hint string
// nine units
// hint number
// 9
// hint default
// 10The hint is string, number or default. Your hook must return a primitive, and the operation then applies its usual rules to that primitive. Returning a number for default is a design choice here, not a language requirement for every object. Avoid expensive work or surprising state changes in implicit conversion.
const value = { [Symbol.toPrimitive]() { return {}; } };
console.log(Number(value));
// ✅ Expected error:
// TypeError: Cannot convert object to primitive valueconst value = { [Symbol.toStringTag]: "Array" };
console.log(Object.prototype.toString.call(value));
console.log(Array.isArray(value));
console.log(value instanceof Array);
// ✅ Expected output:
// [object Array]
// false
// falseA toStringTag changes this diagnostic label. It does not create array internal behavior or prove a value is safe to trust. Symbol.iterator supplies the iterable protocol; Iterators & Iterables teaches that protocol in full. This lesson focuses on how symbol identity selects a protocol hook rather than repeating generator implementation.
Guided exercise: preserve the actual key
Create one symbol, use that same value as the computed key, then discover the field through the symbol-aware reflection method. Each blank has a literal replacement.
const token = ___("label"); // 👉 replace ___ with Symbol
const item = { [___]: "saved" }; // 👉 replace ___ with token
const keys = Object.___(item); // 👉 replace ___ with getOwnPropertySymbols
console.log(keys[0] === token, item[keys[0]]);
// ✅ Expected output:
// true savedBrief: independent registration tokens with bounded retention
Implement createTagStore. register(label) accepts a string whose trimmed length is 1–40 UTF-16 code units. It returns a fresh symbol even if another label matches. Keep at most ten live entries and throw RangeError("store is full") when a valid registration would exceed that limit.
get(token) initially returns undefined. set(token, value) accepts strings of at most 100 UTF-16 code units, including an empty string. revoke(token) removes the entry and frees capacity; any get, set or revoke for an unknown token throws TypeError("unknown token"). Check the token before checking a set value. Expose a live size getter and freeze the API object. Keep the Map in the closure.
These tokens distinguish registrations within this store; they are not authentication credentials and are not JSON-compatible IDs. Revocation removes this store’s reference; it does not erase copies of the symbol held by callers.
function createTagStore() {
const entries = new Map();
const requireToken = token => {
if (typeof token !== "symbol" || !entries.has(token)) throw new TypeError("unknown token");
return entries.get(token);
};
return Object.freeze({
register(label) {
if (typeof label !== "string" || label.trim().length < 1 || label.trim().length > 40) {
throw new TypeError("invalid label");
}
if (entries.size >= 10) throw new RangeError("store is full");
const token = Symbol(label.trim());
entries.set(token, { value: undefined });
return token;
},
set(token, value) {
const entry = requireToken(token);
if (typeof value !== "string" || value.length > 100) throw new TypeError("invalid value");
entry.value = value;
},
get(token) { return requireToken(token).value; },
revoke(token) {
requireToken(token);
entries.delete(token);
},
get size() { return entries.size; }
});
}
const tags = createTagStore();
const first = tags.register(" selection ");
const second = tags.register("selection");
console.log(first === second, first.description, tags.size);
console.log(tags.get(first));
tags.set(first, "alpha");
tags.set(second, "");
console.log(tags.get(first), JSON.stringify(tags.get(second)));
tags.revoke(first);
console.log(tags.size, Object.isFrozen(tags));
try { tags.get(first); } catch (error) { console.log(error.name, error.message); }
// ✅ Expected output:
// false selection 2
// undefined
// alpha ""
// 1 true
// TypeError unknown token
Practice quiz
What does this complete program print? console.log(Symbol("x") === Symbol("x"));
- false
- true
- undefined
- TypeError
Answer: false. Each Symbol call produces a fresh identity.
What does this complete program print? console.log(Symbol.for("x") === Symbol.for("x"));
- false
- true
- undefined
- TypeError
Answer: true. The registered key intentionally retrieves the same symbol.
What does this complete program print? console.log(Symbol.keyFor(Symbol("x")));
- x
- Symbol(x)
- undefined
- null
Answer: undefined. A fresh symbol is not registered, even when it has a description.
What does this complete program print? const s = Symbol("x"); const x = { [s]: 2 }; console.log(Object.keys(x).length, Object.getOwnPropertySymbols(x).length);
- 1 1
- 0 0
- 1 0
- 0 1
Answer: 0 1. The symbol is discoverable through symbol-aware reflection.
What does this complete program print? const s = Symbol("x"); console.log(Object.assign({}, { [s]: 4 })[s]);
- 4
- undefined
- null
- TypeError
Answer: 4. assign copies enumerable own symbol fields.
What does this complete program print? console.log(JSON.stringify([Symbol("x")]));
- []
- [null]
- ["Symbol(x)"]
- undefined
Answer: [null]. A symbol array element is represented by null in JSON.
What does this complete program print? const x = { [Symbol.toPrimitive](hint) { return hint === "string" ? "label" : 4; } }; console.log(String(x), x + 1);
- 4 5
- label 41
- label 5
- [object Object] 5
Answer: label 5. String requests the string hint; addition uses the default hint.
What does this complete program print? const x = { [Symbol.toStringTag]: "Map" }; console.log(Object.prototype.toString.call(x), x instanceof Map);
- [object Map] true
- [object Object] false
- [object Object] true
- [object Map] false
Answer: [object Map] false. A diagnostic tag does not create Map internal behavior.
Continue this course
- Previous: Object Methods (keys, entries, assign, freeze)
- Next: Getters, Setters & Property Descriptors — Computed and validated properties with get/set and defineProperty
- Quick reference: JavaScript cheat sheet