0

Is it possible to create a variable name with input from other variables as described below? Looking at other similar threads, it seems not recommended to use [eval].

I do understand that at a certain amount of variables, it would probably make more sense to group the content in an array, but currently I would like to start understanding if it is possible to solve by building a variable name from other variables.

Below is my code and attempt, using "template literals":

// Players:
  let p1 = "player1";
  let p2 = "player2";
  let activePlayers = p2;

  console.log("Active player: ", activePlayers);

if (activePlayer == "p1") {
  let score_(${p1})_upper_row1;
  let score_(${p1})_upper_row2;
  let score_(${p1})_upper_row3;
} else if (activePlayer == "p2") {
  let score_(${p2})_upper_row1;
  let score_(${p2})_upper_row2;
  let score_(${p2})_upper_row3;
}

Expected produced variable names:

If player is set to [player1]:

score_player1_upper_row1;
score_player1_upper_row2;
score_player1_upper_row3;

If player is set to [player2]:

score_player2_upper_row1;
score_player2_upper_row2;
score_player2_upper_row3;
Toolbox
  • 2,333
  • 12
  • 26
  • 1
    That's not how it works :) I'd suggest using objects for your task. Like `const scores = { [p1]: 0, [p2]: 0}` – Andrey Jan 30 '19 at 11:09
  • @Andrey. Do you mean as node.js uses [module.exports] to build an object with variables for exporting. In the object one can set another name for the object. – Toolbox Jan 30 '19 at 11:12
  • 1
    Think of variables as placeholders in an algorithm. If you dynamically create variable names, you dynamically create placeholders in your algorithm. That means you need an algorithm to deal with your algorithm. That's just nonsense and quickly spirals out of control. – deceze Jan 30 '19 at 11:15
  • @admin: I do not agree that the question already has an answer. In the link you are referring to, it is about calling a variable that is defined as a string. My question is isolated to the method of building a string (with input from variables) that can be directly used as a variable name. – Toolbox Jan 30 '19 at 11:16
  • @deceze: I refer to SO "code-of-ethics". Your answer is somewhat narcissistic and does not give room for SO users to ask questions. I drop the case, though and will not jump into the debate. – Toolbox Jan 30 '19 at 11:19
  • Don't bring ethics into this. The duplicate shows all possible ways how you *can* do "variable variables". Anything else is simply not possible. And the answer always boils down to "don't do this in the first place". – deceze Jan 30 '19 at 11:20

0 Answers0