mechanical-turk
mechanical-turk

Reputation: 801

How to convert a String to a Symbol in JavaScript

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?

Upvotes: 1

Views: 10869

Answers (2)

fdomn-m
fdomn-m

Reputation: 28611

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.

Upvotes: 2

Vasiliy vvscode Vanchuk
Vasiliy vvscode Vanchuk

Reputation: 7159

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 )

Upvotes: 4

Related Questions