Welcome to our comprehensive guide on break and continue in JavaScript! Let's dive into understanding these powerful keywords that can help you navigate through your loops more efficiently.
break and continue 🎯In JavaScript, break and continue are control statements used within loops (for, while, do-while, and for-of). They help us manage the loop flow based on certain conditions, making our code cleaner and more efficient.
While break and continue can make your loops more manageable, use them wisely to avoid overcomplicating your code.
break Statement 📝The break statement is used to exit a loop entirely. When encountered within a loop, it immediately terminates the loop and continues with the next line of code outside the loop.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
// Output:
// 0 1 2 3 4In this example, we loop through numbers 0-9 and print each number. However, once we reach 5, the break statement is executed, causing the loop to terminate, and we print no more numbers.
continue Statement 📝The continue statement is used to skip the current iteration of a loop and move on to the next iteration. It essentially skips the code block within the loop for the current iteration and continues with the next one.
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}
// Output:
// 1 3 5 7 9In this example, we loop through numbers 0-9 and print each odd number. However, when we encounter an even number, the continue statement skips the rest of the current iteration and moves on to the next one, printing no even numbers.
Using continue can help optimize your loops by skipping unnecessary iterations, saving valuable processing time.
In the following code, how many times will the `console.log` statement execute?
Now that you have a better understanding of the break and continue keywords in JavaScript, you can optimize your loops for more efficient and practical code. Happy coding! 🤖🚀