Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the description value of a defined Symbol in JavaScript? [duplicate]

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).

Update

I settled with this hacky solution, until I find a better one :)

const key = Symbol.keyFor(sym) || (sym = sym.toString(), sym.substring(7, sym.length - 1));
like image 266
Yanick Rochon Avatar asked Jul 06 '16 15:07

Yanick Rochon


1 Answers

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';
like image 87
Daniel A. White Avatar answered Oct 19 '22 02:10

Daniel A. White