Break keyword in loops

The break Keyword

Imagine we’re looking to adopt a dog. We plan to go to the shelter every day for a year and then give up. But what if we meet our dream dog on day 65? We don’t want to keep going to the shelter for the next 300 days just because our original plan was to go for a whole year. In our code, when we want to stop a loop from continuing to execute even though the original stopping condition we wrote for our loop hasn’t been met, we can use the keyword break .

The break keyword allows programs to “break” out of the loop from within the loop’s block.

Let’s check out the syntax of a break keyword:

for (let i = 0; i < 99; i++) {
if (i > 2 ) {
break;
} console.log(‘Banana.’);
} console.log(‘Orange you glad I broke out the loop!’);

My question is why do we need the break keyword if the loop will stop running after meeting the condition, anyway?
Wouldn’t it stop and console.log “banana” after meeting the condition – if (i > 2 ) ?

I’m a bit confused.

Run it and find out?

If you think it’ll stop without the break, then you can remove the break and see if it stops.

Thanks for the advice, ionatan. I guess I just have to do practice a lot more until I see the difference between if-else and loops.
I thought if you have and if statement you could log the result, and else for anything else.
if something is === something2
console.log ‘string’
else{
console.log ‘string2’

This is what I thought would handle the same problem without the break.

I’ going back to work :smile: must. learn. JS.

Some reading, if it pleases you.



1 Like

If you run your code, it will log the ‘Banana’ 3 times to the console, because it enters the for loop 3 times, when the ‘i’ is

  • 0
  • 1
  • 2

After this, you add 1 to the i (with the i++, so i will be 3), this condition will be true:
if (i>2) {
break
}
so you will enter this branch, and execute the code in it, which is break, so you’ll ‘break out’ of the for loop

You can also do it by saying
if (‘i === 2’) {

}

because i will never be more than 2 :wink:

1 Like

Thank you for explaining further, Eva!

1 Like