Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Exit Out of the Loop – One Solution

I'd like to add multiple outcomes with if else..

Here's my code.

const main = document.querySelector('main');
const randomNumber = getRandomNumber(10);

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

for (let i = 1; i <= 10 ; i++) {
  let guess = prompt(`Guess the secret number between 1 to 10.`);
  if ( parseInt(guess) === randomNumber && i === 1) {
    main.innerHTML = `<h1>It took you ${i} try to get the number ${randomNumber}.</h1>`;
    break;
  } else if (parseInt(guess) === randomNumber && i < 1) {
    main.innerHTML = `<h1>It took you ${i} tries to get the number ${randomNumber}.</h1>`;
    break;
  } else {
    main.innerHTML = `<h1>You didn't get the number. It was ${randomNumber}.</h1>`;
}

I've added an if else statement and I know that my conditions for the variable "i" aren't written correctly. Can anybody help me to get the proper syntax?

Thank you!

Your else if statement needs to be i > 1 as i will never be smaller than one.

You're right! Although, the program still won't run.

1 Answer

Cameron Childres
Cameron Childres
11,820 Points

Hi Jérôme,

You need to add a final curly brace at the very end to close off your for loop, that will allow your code to run. Combine that with Sean's tip about the else if statement and you're on the right track!

Thanks a lot!