Learn how to use the break and continue statements in your JavaScript programs.
JavaScript has some nifty tools we can use to tweak the behaviors of for loops and while loops. In this tutorial, we’ll learn about break
and continue
.
The break
statement enables us to immediately exit a loop without executing any of the remaining code in the loop. Typically, we use break
statements with a conditional because we want to exit the loop when a specific condition is met. At a high level, a break statement may look like this:
Break + While Loops
break
statements work well with while loops because they avoid repeated code. Take a look at the following code that asks the user to guess a secret number between 1 and 10. This program works, however lines 2 and 6 repeat the same code.
The program below completes the same task but uses a break
statement. Now, instead of repeating the readInt()
command before and inside of the while loop, we just use it once inside the loop.
To do this, we use the condition while(true)
for the loop and move the condition to exit the loop, if(guess == secretNum)
, to the break
statement. While using while(true)
could result in an infinite loop, we avoid this by using a condition with the break
statement.
Run the example below to see the break
statement in action. What happens when you move the println("You win!")
to after the break
statement? Why is this the case?
break
statement in for loops. Take a look at the example for loop below.
break
statement.println(i)
command to before the if statement?While the break
statement immediately exits the loop, the continue
statement immediately returns to the condition of the loop. This enables us to skip specific iterations of the loop without exiting the entire loop. Take a look at the example program below. It’s exactly the same as the for loop above, except that there is a continue
statement where the break
statement was.
continue
statement. println(i)
command to before the if statement?Try your hand at break
and continue
statements in the code editor below. Here are some practice ideas:
readInt(prompt)
command to get a number from the user.