JAVASCRIPT Tutorial
Break and Continue are control statements used in loops to modify the flow of execution. Understanding their functionality is crucial for effective looping.
Loops are used to iterate over collections or execute a block of code multiple times. Break and Continue provide control over this iteration.
const numbers = [1, 2, 3, 4, 5];
// Using Break to exit the loop early
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 3) {
break; // Exit the loop when the value 3 is found
}
console.log(numbers[i]); // Log each number
}
// Using Continue to skip the current iteration
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
continue; // Skip the even numbers
}
console.log(numbers[i]); // Log only the odd numbers
}