When executing loops, standard sequential execution isn't always enough. You may want to exit a loop early when a searched item is found, or skip the current iteration when encountering invalid data. JavaScript provides break and continue for granular loop control.
1. The break Statement: Emergency Exit
The break statement immediately terminates the entire loop and jumps execution to the first statement following the loop:
8 console.log(`Target ${target} found at index ${i}!`);
9break;// Stop looping! No need to check the remaining elements!
10}
11}
Without break, the loop would uselessly continue checking the remaining elements, wasting CPU cycles!
2. The continue Statement: Skip to Next Iteration
The continue statement does not terminate the loop. Instead, it skips the rest of the current iteration and jumps immediately to the next iteration (evaluating the increment and condition):