This is where the break statement comes in.

Find out how the break statement works and why you might need it.

Understanding JavaScript Loops

JavaScript loops let you repeat code, keeping your program clean and reducing repetition.

A green and white exit sign shows a stick figure leaving through a door with a large arrow pointing to the right.

Peter Gudella /Shutterstock

Loops are an important concept that almost every program you write will use.

So, if youre juststarting to learn JavaScript, you should ensure you understand loops thoroughly.

while

Runs a code block as long as a specified condition is true.

do…while

Runs a code block as long as a specified condition is true.

Checks the condition after running the code block, so will always run at least once.

for…in

Runs a code block for eachpropertyof an object.

An Introduction to the “break” Statement

The break statement terminates a loop early.

As the loop progresses, on contact with the break statement, it immediately stops.

This causes the program to move on to the next statement after the loop.

Pay careful attention to the values of local variables and when they are printed or evaluated.

Breaking Out of a for Loop

This code sums an array of elements using a for loop.

The loop iterates over each element of the array, summing them.

The condition checks if the sum exceeds 5.

If so, the break statement terminates the loop.

The loop iterates over each element of the array, calculating the product.

A break statement inside the condition will stop the loop when the product exceeds 10.

The break statement within the if condition checks if the loop counter exceeds 5.

It proceeds to exit the loop if the condition is true.

Here, the condition checks if the loop index is equal to 2.

If it is, it exits the loop using break.

If the loop encounters the value 3 it will exit via the break statement.

Exiting loops early can prevent unnecessary iterations, reduce time complexity, and allow you to handle errors efficiently.

Focus on practicing how to break out of the different JavaScript loops in your programs to strengthen your understanding.