0

Is it possible to create a variable using template strings? Here is a simple example of what I want to achieve:

    let times, hours="fullTime";

    if (hours === "fullTime") {
        times = ["Day", "Night"];
      } else {
        times = ["Day"];
      }

      times.forEach((time) => {
        const `${time}shift` = "8 hours";
      }

      console.log(DayShift);

log: "8 hours"

I want a new variable with a different name to be defined everytime that forEach loop iterates.

Thanks

  • 1
    For global variable, you can use `window[time+"shift"] = "8 hours";`. But you'd probably be better off setting that within a better-scoped JSON object property rather than on the `window` object. – Marc Nov 12 '20 at 16:31
  • 1
    Does this answer your question? [JavaScript: Dynamically Creating Variables for Loops](https://stackoverflow.com/questions/6645067/javascript-dynamically-creating-variables-for-loops) – pilchard Nov 12 '20 at 16:34

1 Answers1

3

Of course, just store them in an object. Simply add keys to the object.

let times, hours = "fullTime";

if (hours === "fullTime") {
  times = ["Day", "Night"];
} else {
  times = ["Day"];
}

let variables = {};

times.forEach((time) => {
  variables[`${time}shift`] = "8 hours";
});

console.log(variables);
console.log(variables.Dayshift);
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63