Symbol.prototype.description

Published · Tagged with ECMAScript ES2019

JavaScript Symbols 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 Symbols without a description, the getter returns undefined:

const symbol = Symbol();
symbol.description;
// → undefined

Symbol.prototype.description support #