JavaScript Symbol
s can be given a description upon creation:
const symbol = Symbol('foo');
// ^^^^^
Previously, the only way to access this description programmatically was indirectly through Symbol.prototype.toString()
:
const symbol = Symbol('foo');
// ^^^^^
symbol.toString();
// → 'Symbol(foo)'
// ^^^
symbol.toString().slice(7, -1); // 🤔
// → 'foo'
However, the code is slightly magical-looking, not very self-explanatory, and violates the “express intent, not implementation” principle. The above technique also doesn’t let you distinguish between a symbol with no description (i.e. Symbol()
) and a symbol with the empty string as its description (i.e. Symbol('')
).
The new Symbol.prototype.description
getter provides a more ergonomic way of accessing the description of a Symbol
:
const symbol = Symbol('foo');
// ^^^^^
symbol.description;
// → 'foo'
For Symbol
s without a description, the getter returns undefined
:
const symbol = Symbol();
symbol.description;
// → undefined
Symbol.prototype.description
support #
- Chrome: supported since version 70
- Firefox: supported since version 63
- Safari: supported since version 12.1
- Node.js: supported since version 12
- Babel: supported