1

Issue: I want to access some variables I got in my js-file by a string.

I know there is an option to receive variable value if you have an object and pass the object key name in square brackets to the object, but this is not the case here. Here I have just one comon variable, and I want its value by "sending" a string down.

Example on what I want to achieve:

const constantName = 12345; // Value to access
const stringToUseToGetTheValueOfConstantName = 'constantName';

// I want to know how to get the '12345' by something like this:
const valueFinallyAccessed = `${stringToUseToGetTheValueOfConstantName}`; // I know this returns a string
console.log(valueFinallyAccessed); // 12345

Solution

const valueFinallyAccessed = eval(stringToUseToGetTheValueOfConstantName);
console.log(valueFinallyAccessed); // Prints out the value 12345
5
  • Also see: stackoverflow.com/questions/5117127/… Commented Sep 12, 2019 at 8:36
  • @HarunYilmaz - works with var not with const or let - unless eval is the answer Commented Sep 12, 2019 at 8:37
  • I didn't try it. I just wanted to share a similar question. Commented Sep 12, 2019 at 8:38
  • 1
    I added to the comment - eval :p Commented Sep 12, 2019 at 8:39
  • @JaromandaX thank you so much, the eval suggestion did work perfectly! I will update my question with the solution Commented Sep 12, 2019 at 9:27

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.