Yanick Rochon Yanick Rochon - 5 months ago 6
Node.js Question

Is it possible to get the description value of a defined symbol in JavaScript?

Suppose I have a symbol such as

const sym = Symbol('foo');
. Now, is there a way to get the value
foo
from that symbol without relying on string manipulations?

I expected
sym.toString()
to return
'foo'
but it returns
Symbol(foo)
.

Answer

There is the Symbol.keyFor. But it only works with the globally registered symbols

const works = Symbol.for('foo');
const key1 = Symbol.keyFor(works); // "foo"

const doesNotWork = Symbol('foo');
const key2 = Symbol.keyFor(doesNotWork); // undefined

I'm guessing that the private symbols do this by design. You could always monkey patch it:

const patched = Symbol('foo');
patched.key = 'foo';