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
DoneThe 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
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.
Add break inside the if, after the printing, so that the loop stops at the first frost. Now only First frost: -3 is printed.