0

I need to find a way to convert any string to a symbol. If there was a function that did that, it would be something like this:

function toSymbol(variable) = {
//... converts var to symbol
};

//toSymbol("mySymbolString") would return: mySymbolString

Is there any clever way of doing this other than storing potential string to symbol mappings in a dictionary?

qeroqazo
  • 741
  • 1
  • 7
  • 9
  • Possible duplicate of [What does this symbol mean in JavaScript?](http://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript) – brianlmerritt May 29 '16 at 15:22
  • 1
    Do you mean a Symbol, as in: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol Or do you mean to a variable? – freedomn-m May 29 '16 at 15:42
  • @freedomn-m i meant it in the second sense. i need it to be a variable. thanks for pointing out the confusion. – qeroqazo May 29 '16 at 16:09

2 Answers2

3
function toSymbol(variable) {
  return Symbol(variable);
};

Keep in mind toSymbol("some_string") === toSymbol("some_string") // false ( by spec. You you need to keep it in true - add memoization )

Vasiliy Vanchuk
  • 6,280
  • 2
  • 18
  • 39
  • 3
    You can use global symbols by using [`Symbol.for()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for) instead. – GingerPlusPlus May 29 '16 at 15:30
1

I need it to be a variable.

All global variables are actually a property of window

eg:

window.abc = 123
abc == 123

you can also reference properties using strings, eg:

window["abc"] = 123
window.abc == 123
abc == 123

If you're using namespaces or objects, then it's just the same, eg:

My.Namespace["variable"]=value
My.Namespace.variable == value

This gives your example "variable":

window["variable"] = value

it's not clear what you want to do with this, but you could make it = null or = {} to use later.

freedomn-m
  • 21,261
  • 4
  • 28
  • 53
  • I needed this once. It was some utility function meant to be used in debugging/development on the JS console, and the utility function did an XMLHttpRequest. And you could pass an extra string variable to the utitlify function, and that then became the global variable name (global = in window) of the result of the XMLHttpRequest. And if you didn't specify the variable name, it was called result42, result43, etc. So, it's not even *that* weird wanting to do this! – mathheadinclouds Jul 23 '20 at 09:53