The Break Statement
Now let's look at the break
statement, which allows us to exit a loop prematurely. Imagine you want to buy a house, and you go looking at houses for sale every day. Once you buy a house, you don't want to continue looking at houses the following days because you already have one. The break
statement allows you to do this. The break
statement terminates the ongoing loop.
For example, we want to find the first even number between 1
and 10
:
let number = 1;
while (number <= 10) {
if (number % 2 === 0) { // If the number is even
console.log(number);
break; // Exit the loop
}
number++;
}
This prints:
2
In this example, we go through the numbers from 1
to 10
. As soon as we encounter the first even number, we print it and exit the loop using break
.
Without break
, the loop would continue and print all the even numbers in the sequence.
To explain the condition number % 2 === 0, the % operation returns the remainder after division, and when the remainder after dividing number
by two is 0, it means that number
is even.
Instructions
Create a variable count
with an initial value of 1.
Using a while
loop, iterate count
from 1 to 10 and print count
when it is greater than 5, then exit the loop. Use the break
statement to do this. Remember to increment the count
variable by 1.
Start programming for free
5/9