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 JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Break out the loop

Hi guys, can you tell me why Dave speak to have some solutions to break out the loop if we already have a counter that can stop the loop after a given cycle of 10 attempts for example? Not clear this point. Thanks

2 Answers

Hi Luca,

There are two ways to break out of a loop: when the loop ends or we use the keyword "break"

Let's pretend that we have created a guessing app that allows user to guess a number 10 times, and let's say the user guessed it right before it reaches its limit.

In this case, we don't want a user to continue to guess after he/she guesses the correct answer, and that's where break comes in handy. We could use it to immediately break the loop and stop the prompting window from opening after the user guesses the answer right.

var answer = 50;
for (var i = 0; i < 10; i++) {
  var guessed = prompt("please guess a number");
  if (parseInt(guessed) === answer) {
     alert(`You guessed right! The correct answer is ${answer}!`);
     break;
  }
}

Without the break statement, the loop will continue to run till it reaches the condition, i < 10 meaning the code will run even after the user has guessed the right answer.

Hope this helps! -Chris

Thanks Chris for the answer! ;-)