JavaScript Exit Out of the Loop – One Solution

I need a new set of eyes to just look over my code please.

https://w.trhou.se/q3u1b7buls Please forgive lines 9 and 24 I find it easier to separate blocks of code. I'm really after any advice of line 15 let triesLeft = (10 - i); I am trying to find out if this is acceptable.

I tried to break the program / cause a deliberate bug to see if its not suitable, nothing so far.

Thanks for any advice about anything. :-)

2 Answers

Mark Sebeck
MOD
Mark Sebeck
Treehouse Moderator 28,625 Points

Hi Jason. Looks like line 15 is ok. I'm not sure I like the else statement on the if. Seems like there should be a better way than to keep setting the message each time they miss. One way I can think of would be set the message when you initialize message. If they get it right message will be over written with the winning message. If not it will print the losing message.

const main = document.querySelector('main');
const randomNumber = getRandomNumber(10);
let message = `<p>Sorry you didn't guess the right number.  It was ${randomNumber}</p>`;

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

//==========================================================================

for ( let i = 1; i <= 10; i++ ) {     // i is equal to the deleted guessAttempts.
  let guess = prompt("I am thinking of a number between 1 and 10. What is it?");

  if ( parseInt(guess) === randomNumber ) {
    let triesLeft = (10 - i);
    message = `<p>You used ${i} attempts to guess the random number <strong>${randomNumber}.</strong></p>
                  You had ${triesLeft} attempts left to try.`;
    break;
  } 
}

//===========================================================================

Also I think I would make your for statement block a function to clean it up a bit.

If you make it a function you could return the winning message in the IF statement, and have a return for the losing message outside the loop.

function {
  for ( let i = 1; i <= 10; i++ ) {     // i is equal to the deleted guessAttempts.
    let guess = prompt("I am thinking of a number between 1 and 10. What is it?");

    if ( parseInt(guess) === randomNumber ) {
      let triesLeft = (10 - i);
      message = `<p>You used ${i} attempts to guess the random number <strong>${randomNumber}.</strong></p>
                  You had ${triesLeft} attempts left to try.`;
      return message;
    } 
  }
   return <losing message>

}

I'm sure there are other ways but most important is it working which I believe yours is.

Thanks for your reply Mark Sebeck, all the code (apart from line 15) is from a practice session consisting four videos from Guil the teacher, I'm learning and trying not to over complicate things for myself, however you have a good point code can always be improved, I tend to leave it as long as I get the result I'm after and its readable, I wasn't sure about line 15 thanks for the advice though...