Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

The break Statement

Sometimes you don't need to go through the whole array. When you are looking for something and you find it, there is no reason to keep looking. The break statement ends the loop immediately, and the program continues with the code after the loop.

Let's find the first even number in an array. The loop prints each number it checks, so that you can see where it stops:

const numbers = [7, 13, 22, 9, 40];
for (const number of numbers) {
    console.log("Checking", number);
    if (number % 2 === 0) {
        console.log("First even number:", number);
        break;
    }
}
console.log("Done");
Checking 7
Checking 13
Checking 22
First even number: 22
Done

The condition number % 2 === 0 is true for even numbers: the remainder after dividing them by 2 is 0. When the loop gets to 22, the condition is true. The program prints the result, and break ends the loop: 9 and 40 are never checked, and the program goes on with console.log("Done"). Without break, the loop would continue and also print First even number: 40, which is wrong, because 40 isn't the first one.

You will almost always put break inside an if. On its own, it would end the loop during its very first iteration. break works the same way in while and for loops.

Instructions

  1. 1

    The array temperatures holds morning temperatures in the order they were measured. Write a loop that goes through it and, for every temperature below zero, prints First frost: and the temperature. Run the program: it prints three lines, but only the first one is right.

  2. 2

    Add break inside the if, after the printing, so that the loop stops at the first frost. Now only First frost: -3 is printed.

Back

8/12

  1. 1. The while Loop
  2. 2. Shorter Notation
  3. 3. The for Loop
  4. 4. Looping Through Arrays
  5. 5. Sum and Average
  6. 6. Counting
  7. 7. The Largest Value
  8. 8. The break Statement
  9. 9. The continue Statement
  10. 10. Loops and Text
  11. 11. Nested Loops
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.