Sub topic 2
Descriptions, toString, and Why Symbols Refuse Implicit Conversion
This chapter assumes you know JavaScript's primitive types, typeof, template literals, and the basics of type coercion. It also builds on the previous chapter: every call to Symbol() returns a new, unique value.
The description is a label
You can pass Symbol() an optional argument called the description. The description is only there to help you debug. It has no effect on the symbol's identity, so two symbols with the same description are still different values.
const a = Symbol('id');
const b = Symbol();
const c = Symbol('');
const d = Symbol(42);
console.log(a.description); // "id"
console.log(b.description); // undefined
console.log(c.description); // ""
console.log(d.description); // "42" (the argument is converted to a string)The description property is read-only. It also tells "no description" apart from "empty description". Symbol() gives undefined, while Symbol('') gives an empty string. The older trick of parsing the output of toString() cannot make that distinction, because both symbols print as "Symbol()".
Explicit conversion works
To get a string from a symbol, you have to ask for one explicitly:
const s = Symbol('x');
console.log(s.toString()); // "Symbol(x)"
console.log(String(s)); // "Symbol(x)"
console.log(s.description); // "x"
console.log(Boolean(s)); // true
console.log(!s); // falseString(s) is a special case in the spec. It checks for a symbol and calls the symbol's own descriptive conversion, so it does not throw. Boolean conversion is also allowed, and every symbol is truthy. That means if (sym) behaves as you would expect.
Implicit conversion throws
Any operation that silently coerces a symbol to a string or a number throws a TypeError:
const s = Symbol('x');
const attempts = [
() => s + '',
() => `${s}`,
() => +s,
() => s * 2,
() => [s].join(','),
];
for (const attempt of attempts) {
try {
attempt();
} catch (e) {
console.log(e instanceof TypeError, e.message);
}
}
// true "Cannot convert a Symbol value to a string" (wording varies by engine)Template literals are where most people hit this. ` ${s} ` looks harmless, but it runs the same abstract ToString operation as concatenation, and that operation rejects symbols.
Why the language refuses
Symbols exist to be property keys that can never collide with string keys. Suppose implicit conversion were allowed:
const tag = Symbol('tag');
const obj = {};
// If this silently converted, the key would become the string "meta:Symbol(tag)",
// which any code can recreate by typing that string.
// obj['meta:' + tag] = true; // actually throws TypeError
obj[tag] = true; // correct: the symbol itself is the keyIf 'meta:' + tag produced the string "meta:Symbol(tag)", you would have an ordinary string key that anyone can recreate by typing it, and the collision protection would be gone without any warning. Throwing turns that mistake into an error you see at once. Using a symbol directly as a key, as in obj[tag], is fine, because property-key conversion keeps symbols as symbols.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| `` `key: ${sym}` `` in a log message | TypeError | `` `key: ${sym.toString()}` `` or `String(sym)` |
| Parsing `sym.toString()` to get the label | Fragile, cannot tell `undefined` from `''` | Use `sym.description` |
| Expecting matching descriptions to mean equal symbols | Comparison is always `false` | Compare the symbol references themselves |
| `obj['prefix' + sym]` | TypeError | Use `obj[sym]` |
Exercise
What does each line print or throw? (1) String(Symbol()) (2) Symbol('').description === undefined (3) ` ${Symbol('a')} (4) Symbol('a').description === Symbol('a').description`
Show answer
(1) "Symbol()" (2) false, because the description is the empty string "" (3) throws a TypeError, because template literals coerce implicitly (4) true, because the descriptions are equal strings even though the two symbols are not equal.
Exercise
Write a function label(value) that returns a readable string for any value, including symbols, without throwing.
Show answer
function label(value) { return typeof value === 'symbol' ? value.toString() : String(value); } Plain String(value) also works for symbols, but the explicit check makes the intent clear and lets you format symbols differently if you need to, for example with value.description ?? '(no description)'.