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.
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.
Find the number 5 in the array and add a conditional statement to break the loop when the number is found.
if statement inside the
for loop that checks if the current element is equal to 5.
break keyword inside the
if statement to exit the loop.
Sign up to start coding
Already have an account?