Code Highlights logo

Learn

Loops

The break Keyword

Imagine you have a loop that is iterating over an array and you want to stop the loop as soon as you find a specific element. Without the break keyword, the loop would continue until it reaches the end of the array, even if the desired element has already been found. By using the break keyword, you can instantly exit the loop once the condition is met, saving valuable processing time and improving overall efficiency.

Syntax and Usage

1for (let i = 0; i < array.length; i++) {
2 if (array[i] === targetElement) {
3 // execute desired code
4 break;
5 }
6}

In the above example, we use the break keyword inside the loop's body as soon as we find the targetElement in the array. This immediately terminates the loop, skipping any remaining iterations.


Instructions

1.

Find the number 5 in the array and add a conditional statement to break the loop when the number is found.

  • Add an if statement inside the for loop that checks if the current element is equal to 5.
  • Use the break keyword inside the if statement to exit the loop.

Sign up to start coding

Already have an account?

Sign In

Course content