Yanick Rochon Yanick Rochon - 1 year ago 33
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
from that symbol without relying on string manipulations?

I expected
to return
but it returns

Answer Source

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';