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?
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?
Share Improve this question asked May 29, 2016 at 15:17 mechanical-turkmechanical-turk 8012 gold badges8 silver badges9 bronze badges 3- Possible duplicate of What does this symbol mean in JavaScript? – brianlmerritt Commented May 29, 2016 at 15:22
- 1 Do you mean a Symbol, as in: developer.mozilla/en/docs/Web/JavaScript/Reference/… Or do you mean to a variable? – fdomn-m Commented May 29, 2016 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. – mechanical-turk Commented May 29, 2016 at 16:09
2 Answers
Reset to default 4function 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 )
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.