1

I've made a JavaScript 'while' loop to keep adding a random number from 1 to 10 to an array until the random number is 9 or 10.

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

var array = [];
var element = 0;
while (element < 9) {
    element = random();
    if (element < 9) {
        array.push(element);
    }
}
console.log(array);

I have two questions.

  1. How can I make the 'while' loop more elegant - without using (element < 9) two times?

  2. How can I do this in a more elegant way, without using a 'while' loop?

5
  • 4
    You definitely want a while loop because you're doing something while a condition is true. Try while( (element = random()) < 9) array.push(element);. Commented Jul 3, 2017 at 18:55
  • @Santi They generate a new random number inside the loop so it's needed for this specific algorithm Commented Jul 3, 2017 at 18:55
  • @AndrewLi I noticed this and deleted my comment, though I suppose I would have just re-ordered the random() and the .push, initializing element as random() instead of 0. EDIT: Seems cᴏʟᴅsᴘᴇᴇᴅ suggested the same thing as me, though Niet's answer is likely best. Commented Jul 3, 2017 at 18:56
  • @NiettheDarkAbsol That's an even better alternative to what I suggested. Should I delete my answer? Commented Jul 3, 2017 at 18:57
  • @NiettheDarkAbsol That's exactly what I was looking for - perform the assignment and check in one step. Thanks! Commented Jul 3, 2017 at 21:12

1 Answer 1

2

To answer your first question, you can initialise element with a random value to begin with:

var element = random();
while (element < 9) {
    array.push(element);
    element = random();
} 

This gets rid of the inner if.

To answer your second question, it doesn't get more elegant than this really. If you really want to use something else, you could use a do-while by changing around your code but really it's the same thing.


An even better alternative (I credit @NiettheDarkAbsol) for this, is to perform the assignment and check in one step:

while ((var element = random()) < 9) {
    array.push(element);
} 

You eliminate the need to even declare it outside, or call random() in more than one place.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.