-2

I know you can use arrays but is there a way to declare multiple variables quickly - lets say up to 50 using a loop and an integer at the end of each variable going up by one every time.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p id="demo"></p>

<script>
var price1 = 5;
var price2 = 6;
var price3 = 7;
var price4 = 8;
var price5 = 4;
var price6 = 1;
var price7 = 9;
var price8 = 8;
var total = price1 + price2 + price3 + price4 + price5 + price6 + price7 + price8;
document.getElementById("demo").innerHTML =
"The total is: " + total;
</script>

</body>
</html>
Charlie
  • 22,886
  • 11
  • 59
  • 90
  • 1
    pseudo: `for(whatever) window['price'+N] = val;` ... but it's not good code so I refuse to post it as an answer. – Emissary Jan 21 '16 at 09:39
  • Including a reason for that need would be helpful, because automatically declaring a set of global variables sounds like an anti-pattern. Even one global variable is one too many and with an array you get all the manipulation methods as well. – hon2a Jan 21 '16 at 09:43
  • if i am using arrays what is the quickest way to declare array of 50 elements all integers at the value of 0 – Nicholas Mason Jan 21 '16 at 09:45

2 Answers2

0

I know you can use arrays

Yes. And you absolutely should use arrays for that purpose. It is what are designed for.

is there a way to declare mutiple variable quickly

Only if you create global variables. Globals are awful.

window["price" + i] = somevalue;
Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

If you don't want to use an array and if eval still is considered an evil even for this simple operation, you can go for an object. Lets say you create an object with all the variables you need as properties and done by loop.

var myVars = {};

for (var i = 0; i < 50 i++) {
   myVars['price' + i] = 0;
}
Charlie
  • 22,886
  • 11
  • 59
  • 90