-1

Is it possible to dynamically select a variable based on the value of another variable in JavaScript? For example, let's say I have 4 variables:

var one = 'Apple',
    two = 'Orange',
    three = 'Banana',
    selector = prompt('Type one, two, or three');

console.log(`You chose ${whatever string is contained within selector}`);

Is it possible to console.log the variable that has the name matching the string contained in selector? Example: user inputs "one", console.log displays Apple, user inputs two, console.log displays Orange, etc.

Obviously this can be done with an if or a switch, and with only 3 variables to differentiate between that wouldn't be too hard. However, this is for a Discord bot I'm building, and in the process I am finding it would be helpful for debugging purposes if I could ask the bot to output the value of a given variable at a certain point in the runtime. I'm hoping to write some bit of code that will allow me to input something like !print someVariableName and my code will call a function which prints the value contained in the variable whose name is contained in someVariableName at that time.

I'm using Node.js, if that makes a difference - maybe there's an NPM package that does this already.

  • I suggest that you make an object, such as `const options = {one: 'Apple', two: 'Orange', three: 'Banana'}`, then index the object using bracket-notation to get the value you're after, `options[selector]` – Nick Parsons May 02 '21 at 00:05
  • Thanks for the idea! I was hoping that this could be dynamic to the point of not needing to hard-code every variable I might want to return. I.e., I create a new var called `four` and I can check that without needing to add it to the `options` object, but it seems like this might be the only way to go. – binaryBrandon May 02 '21 at 02:34

1 Answers1

0

Is not a GOOD IDEA use eval, as it enables users to run malicious code!

If you really want to follow this way, try that:

var options = ['one', 'two', 'three']
var one = 'Apple',
    two = 'Orange',
    three = 'Banana',
    selector = prompt(`Chose [${options.join('-')}]`);

if (options.includes(selector)){
  console.log(`You chose ${eval(selector)}`);
}
Marcus Yoda
  • 243
  • 1
  • 8
  • This code won't work/run and is dangerous. Firstly, `.join(-)` will throw an error, as you're missing quotes `'-'`. Then, you should be checking if `options` includes the selector, not that the selector includes the options, so you need, `options.includes(selector)`. Then `eval(one)` won't work either, as this will evaluate to `Apple`, but there is no variable called Apple. It would need to be `eval(selector)`. However, using `eval()` on user input is never a good idea as it enables users to run malicious code – Nick Parsons May 02 '21 at 00:00
  • 1
    you are totally right, i rewrite and need more coffee... – Marcus Yoda May 02 '21 at 00:02