Christopher
Christopher

Reputation: 123

For Loop vs. Do…While

Background

I'm just learning JavaScript and I thought that a good way to start was to code my own dice roller for an RPG I play. For this game you roll a handful of six-sided dice where each 4 or 5 is worth one success and each 6 is worth 2 successes.

I have a function that rolls the dice and passes the rolls, via an array, to another function that HTML-ifies it for display on the webpage.

The Code

In order to roll the dice, I have what I think is the standard dice roller function (the sides variable is because sometimes you can roll dice that have sides other than 6, so I made the function usable for all dice rolls):

function rollDice(sides) {
  return Math.floor(Math.random()*sides) + 1;
}

Because the number of dice you roll varies, my main function calls this rollDice() function a number of times and puts each result in an array.

This is the main function, where number is the number of dice to roll:

function dice(number) {
  let results = [];
  for (i=0; i<number; i++){
    results.push(rollDice(6));
  }
  return results;
}

However, I have since learned of the do…while loop, and have managed to refactor it thusly:

function dice(number) {
  let results = [];
  do {
    results.push(rollDice(6));
  } while (results.length < number)
  return results;
}

The Actual Question

Which loop is more 'correct' or best practice to use? for or do…while?

Upvotes: 2

Views: 127

Answers (1)

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

You can just use a simple while loop which is equivalent to your for loop example.

function dice(number) {
  let results = [];
  while (results.length < number) {
    results.push(rollDice(6));
  }
  return results;
}

I like the readability of this the best (partly because it doesn't create an extra iterator variable), but the for loop is fine too. The do...while loop works but the extra syntax is unnecessary.

Upvotes: 1

Related Questions