About Lesson
Loop Control: break, continue
1. break
Terminates the loop entirely.
Example:
JavaScript
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i); // Prints 0, 1, 2
}
Example with break
:
Let’s say you have a list of numbers and you’re looking for the first number greater than 5.
JavaScript
let numbers = [1, 2, 3, 6, 8, 9];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > 5) {
console.log("Found a number greater than 5:", numbers[i]);
break; // Stop the loop when the first number greater than 5 is found
}
}
Output:Found a number greater than 5: 6
2. continue
Skips the current iteration and proceeds to the next one.
Example:
JavaScript
for (let i = 0; i < 5; i++) {
if (i === 3) continue;
console.log(i); // Prints 0, 1, 2, 4
}
Example with continue
:
Now, let’s say you want to print only the numbers greater than 5, skipping all others.
JavaScript
let numbers = [1, 2, 3, 6, 8, 9];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] <= 5) {
continue; // Skip the current iteration if the number is less than or equal to 5
}
console.log(numbers[i]);
}
Code Output:6
8
9