0

Observe the following:

let gamesArray = ['Shadow of the Beast 2', 'Flashback', 'Turricain 2', 'Gods', 'Speedball 2', 'First Samurai', 'Beneath a steal sky', 'Magic Pockets', 'Superfrog', 'Final Fight'];
let [Game_1, Game_2, Game_3, Game_4, Game_5, Game_6, Game_7, Game_8, Game_9, Game_10] = gamesArray;

console.log(Game_8); // Magic Pockets
console.log("\n");

I was wondering that if we were unpacking 10 array elements as separate variables and wanted to call them Game_[an incremented number] how would we go about it ? I was trying a few things by running the code in Atom text editor with JS enabled.

obviously a small array is easy to unpack and refer back to as opposed to an array with ten elements as seen in the above example.

Anybody got any ideas ?

  • i.e instead of manually typing the variable names 'Game_1, Game_2' wouldn't it be better to use a for-of loop and then dynamically create each variable name ? – Manoj Kumar Jan 02 '21 at 17:59
  • 2
    No, this is not possible, and it makes no sense to use dynamic variable names. Just `console.log(gamesArray[8])`! – Bergi Jan 02 '21 at 18:02
  • In JS, the variables are static. You have to use objects (e.g. arrays) to have dynamic keys. – FZs Jan 02 '21 at 18:23
  • 1
    Duplicate of [JavaScript: Dynamically Creating Variables for Loops](https://stackoverflow.com/questions/6645067/javascript-dynamically-creating-variables-for-loops) – FZs Jan 02 '21 at 18:28
  • Thanks for notifying us all @ FZs This helped me somewhat, geekforgeeks.. https://www.geeksforgeeks.org/how-to-use-dynamic-variable-names-in-javascript/ I was already trying something similar and almost did it in a bespoke way without geek4geeks link. – Manoj Kumar Jan 02 '21 at 19:40

0 Answers0