Sub topic 2
Descriptions, toString, and Why Symbols Refuse Implicit Conversion
This chapter assumes you know JavaScript's primitive types and typeof, and that you have read the previous chapter. In that chapter you learned that every call to Symbol() returns a new, unique value. Here you will learn what the text inside Symbol('...') actually does, how to turn a symbol into a readable string, and why JavaScript throws a TypeError when you try to convert a symbol without asking for it explicitly.
The Description Is a Label, Not an Identity
When you write Symbol('id'), the string 'id' is the symbol's description. A description is an optional label meant for humans: it shows up in debuggers, console output, and error messages. It plays no part in identity, so two symbols with the same description are still different values.
const a = Symbol('id');
const b = Symbol('id');
console.log(typeof a); // "symbol"
console.log(a === b); // false
console.log(a.description); // "id"
console.log(a.toString()); // "Symbol(id)"
// new Symbol('id'); // TypeError: Symbol is not a constructorThink of the description as a sticky note on a box. You can put identical notes on two boxes, and they are still two boxes.
How the description argument is processed
Symbol(arg) converts its argument to a string with the standard string conversion, unless the argument is undefined. That leads to some cases worth knowing:
console.log(Symbol().description); // undefined
console.log(Symbol(undefined).description); // undefined
console.log(Symbol('').description); // ""
console.log(Symbol(42).description); // "42"
console.log(Symbol(null).description); // "null"
console.log(Symbol({}).description); // "[object Object]"
console.log(Symbol([1, 2]).description); // "1,2"A missing description and an empty one are different. Symbol() has the description undefined, while Symbol('') has the description "". Passing an object means its toString result becomes the description, which is rarely what you want. Pass a string literal.
The `description` property
description is a read-only getter on Symbol.prototype, added in ES2019. Reading sym.description works because JavaScript temporarily wraps the primitive in a Symbol object to look up the property, the same way 'abc'.length works for strings.
const s = Symbol('token');
s.description = 'changed'; // ignored (throws in strict mode... see below)
console.log(s.description); // "token"Built-in symbols have descriptions too. Symbol.iterator.description is "Symbol.iterator". That is why the console shows well-known symbols with readable names.
Explicit Conversion: The Ways That Work
You can always get a string from a symbol if you ask for it directly. There are three explicit routes.
const s = Symbol('x');
console.log(String(s)); // "Symbol(x)"
console.log(s.toString()); // "Symbol(x)"
console.log(s.description); // "x"String(s) and s.toString() both produce the descriptive string: the text Symbol(, the description, and ). description gives you the raw label without the wrapper.
Choose based on what you need:
| Goal | Use | Result for `Symbol('x')` | Result for `Symbol()` |
|---|---|---|---|
| Log or show a symbol in a message | `String(s)` or `s.toString()` | `"Symbol(x)"` | `"Symbol()"` |
| Get just the label | `s.description` | `"x"` | `undefined` |
| Tell `Symbol()` from `Symbol('')` | `s.description` | `"x"` | `undefined` (vs `""`) |
The descriptive string cannot distinguish Symbol() from Symbol(''): both print "Symbol()". Before ES2019, people parsed toString() output to extract the label. Use description instead.
`String(s)` works, but `new String(s)` does not
String called as a plain function has a special case for symbols that returns the descriptive string. Called with new, it runs the ordinary string conversion, and that conversion throws.
const s = Symbol('x');
console.log(String(s)); // "Symbol(x)"
try {
new String(s);
} catch (e) {
console.log(e instanceof TypeError); // true
}Implicit Conversion: The Ways That Throw
Implicit conversion happens when JavaScript converts a value for you because an operator or function needs a string or number. Symbols refuse both.
const s = Symbol('x');
console.log(String(s)); // "Symbol(x)"
try {
console.log(s + '');
} catch (e) {
console.log(e instanceof TypeError); // true
}The same TypeError appears in many places that hide a string or number conversion:
const s = Symbol('x');
const attempts = {
concatenation: () => 'key: ' + s,
template: () => `${s}`,
unaryPlus: () => +s,
numberCall: () => Number(s),
arithmetic: () => s * 2,
arrayJoin: () => [s].join(','),
parseInt: () => parseInt(s),
};
for (const [name, fn] of Object.entries(attempts)) {
try {
fn();
console.log(name, 'ok');
} catch (e) {
console.log(name, '->', e.constructor.name);
}
}
// concatenation -> TypeError
// template -> TypeError
// unaryPlus -> TypeError
// numberCall -> TypeError
// arithmetic -> TypeError
// arrayJoin -> TypeError
// parseInt -> TypeErrorNote that Number(s) throws even though it looks explicit. Unlike String, Number has no special case for symbols. A symbol has no sensible numeric value.
Operations that do not convert, and so do not throw
Some operations look like conversions but never need a string or number:
const s = Symbol('x');
console.log(Boolean(s)); // true
console.log(!!s); // true
if (s) console.log('truthy'); // "truthy"
console.log(s == 'Symbol(x)'); // false
console.log(s == 'x'); // false
console.log(JSON.stringify(s)); // undefined
console.log(JSON.stringify([s])); // "[null]"
console.log(Object.prototype.toString.call(s)); // "[object Symbol]"
console.log(typeof Object(s)); // "object"- Boolean conversion never throws. Every symbol is truthy.
- Loose equality (
==) between a symbol and a string or number just returnsfalse. It does not convert, so it does not throw. JSON.stringifyskips symbols. A top-level symbol givesundefined, and a symbol inside an array becomesnull.Object(s)wraps the symbol in aSymbolobject without converting it.
Here is the decision path JavaScript follows:
Why the Language Throws
The rule exists to protect uniqueness. Suppose symbols silently became strings. A common way code builds property keys is concatenation or interpolation:
const id = Symbol('id');
const obj = {};
// If this silently produced "Symbol(id)", every symbol described as "id"
// would map to the same string key, and uniqueness would be lost.
try {
obj[`${id}`] = 1;
} catch (e) {
console.log(e.message.includes('Symbol')); // true
}
obj[id] = 1; // correct: a symbol key
console.log(Object.getOwnPropertySymbols(obj).length); // 1Silent conversion would turn Symbol('id') into the string "Symbol(id)". Two unrelated libraries using Symbol('id') would then collide on the same string key, which is exactly the problem symbols solve. Throwing makes that bug visible at the line where it happens.
Property access is the important exception. obj[s] converts its key with a property-key conversion, which keeps symbols as symbols and converts everything else to a string. So symbols work as keys, as the next chapter shows, without ever becoming strings.
Common Errors and Fixes
Logging and error messages
The most frequent real-world failure is building a message that includes a symbol:
const state = Symbol('loading');
function describe(value) {
// return 'State is ' + value; // TypeError for symbols
return `State is ${String(value)}`;
}
console.log(describe(state)); // "State is Symbol(loading)"
console.log(describe('ready')); // "State is ready"Wrapping the value in String() is safe for every type, including null, undefined, and symbols. That makes it a good habit in generic logging helpers that might receive any value. console.log(state) also works, because the console formats values itself instead of converting them to strings.
Tagged templates are an escape hatch
A tagged template passes interpolated values to the tag function unchanged. The TypeError only happens if the tag converts them implicitly:
function safe(strings, ...values) {
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? String(values[i]) : ''),
''
);
}
const s = Symbol('job');
console.log(safe`Running ${s} now`); // "Running Symbol(job) now"Sorting and joining collections
Array.prototype.join and the default sort comparator both convert elements to strings, so an array that contains symbols will throw. Map first:
const tags = [Symbol('b'), Symbol('a')];
const labels = tags.map((t) => t.description).sort();
console.log(labels.join(', ')); // "a, b"Sorting by description is fine for display. Do not use the description to find or compare symbols: two different symbols can share a description, and comparing descriptions would make them look equal.
Summary
- The description is a debugging label. It never affects equality.
Symbol()has anundefineddescription.Symbol('')has an empty string description.String(s),s.toString(), ands.descriptionare the explicit, working conversions.- Implicit string conversion (
+, template literals,join) and every numeric conversion, includingNumber(s), throw aTypeError. - Boolean conversion, loose equality,
JSON.stringify, and property-key use do not throw. - The throwing rule exists so symbols cannot quietly turn into colliding string keys.
Exercise
What does each line print, or does it throw? (1) Symbol().description (2) String(Symbol('')) (3) Symbol(7).description === '7' (4) ` ${Symbol('a')} `
Show answer
(1) undefined. (2) "Symbol()". (3) true, because the argument is converted to the string "7". (4) It throws a TypeError, because template literals convert interpolated values to strings implicitly.
Exercise
A logging helper is written as function log(label, value) { console.log(label + ': ' + value); }. Calling log('key', Symbol('id')) throws. Rewrite it so it works for every type of value, and explain why console.log('key:', value) would also have worked.
Show answer
Use function log(label, value) { console.log(label + ': ' + String(value)); }. String() has a special case for symbols and returns "Symbol(id)". Passing the symbol as a separate argument to console.log also works, because the console formats each argument itself instead of applying string concatenation.
Exercise
A teammate writes cache[String(key)] = data where key is a symbol, "to avoid the TypeError". What goes wrong?
Show answer
The property is stored under the plain string key "Symbol(description)", not under the symbol. It becomes enumerable, appears in Object.keys and JSON.stringify, and collides with any other symbol that has the same description. Reading cache[key] with the symbol also misses it. The fix is cache[key] = data, since property access keeps symbols as symbol keys.
Exercise
Why is Boolean(Symbol('x')) allowed while Number(Symbol('x')) throws?
Show answer
Converting to boolean only asks whether the value is truthy, and every symbol is truthy, so there is no ambiguity. A symbol has no meaningful numeric value, and Number() has no special case for symbols, so the numeric conversion throws a TypeError rather than inventing a number such as NaN.