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
RMT
  • 942
  • 2
  • 12
  • 32

0 Answers0