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

2
  • 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. Commented Nov 12, 2020 at 16:31
  • 1
    Does this answer your question? JavaScript: Dynamically Creating Variables for Loops Commented Nov 12, 2020 at 16:34

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.