Is there a way to get a variable by a given string

Viewed 52

You have a variable:

const test = "Some random value."

and the name of the variable in a string format:

const input = "test"

is there a way to get the value without a enum?

console.log(someMagicFunction(input))

$ => "Some random value."

Thanks!

1 Answers

Short answer - no.

You are kind of describing the behavior of a pointer - sort of... You want to get what is stored in memory and referenced as the variable test. JS does not support that.

There are things you could do such as store the keys and values in a hash map (an object) and have a similar effect.

const store = {
    test: "Some random value.",
    foo: "bar"
};

const magicHappensHere = (key) => {
    return store[key];
};

console.log(magicHappensHere('test')); // "Some random value."
Related