1 Answers
π Definition of 'continue' Statement in JavaScript
The continue statement in JavaScript is used within loops (like for, while, and do...while) to skip the rest of the current iteration and move on to the next one. Think of it as saying, "Okay, I'm done with this round; let's go to the next one!"
π History and Background
The continue statement has been a part of JavaScript since its early days. It was included to provide developers with more control over loop execution, allowing them to bypass certain parts of the loop based on specific conditions. This feature is borrowed from languages like C and C++, ensuring that JavaScript developers have a familiar and powerful tool for managing loops.
π Key Principles
- βοΈ Skipping Iterations: The main job of
continueis to skip the rest of the code inside the loop for the current iteration. - π Loop Continues: It doesn't stop the entire loop; it just moves to the next iteration.
- π― Conditional Use: It's usually used with an
ifstatement to decide when to skip.
π» Real-world Examples
Let's look at some practical examples to understand how continue works.
Example 1: Skipping Even Numbers
This example shows how to skip even numbers in a loop:
for (let i = 0; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // Output only odd numbers
}
Example 2: Processing Specific Array Elements
Here's how to use continue to process only certain elements in an array:
const myArray = [10, 20, 30, -5, 40, -10];
for (let i = 0; i < myArray.length; i++) {
if (myArray[i] < 0) {
continue; // Skip negative numbers
}
console.log(myArray[i]); // Output only positive numbers
}
Example 3: Avoiding Division by Zero
Using continue to avoid errors when dividing by zero:
for (let i = -2; i <= 2; i++) {
if (i === 0) {
continue; // Skip division by zero
}
const result = 10 / i;
console.log(`10 / ${i} = ${result}`);
}
π‘ Conclusion
The continue statement is a handy tool in JavaScript for controlling the flow of loops. It allows you to skip specific iterations based on conditions, making your code more efficient and readable. Understanding how to use continue will help you write cleaner and more effective loops in your programs.
Join the discussion
Please log in to post your answer.
Log InEarn 2 Points for answering. If your answer is selected as the best, you'll get +20 Points! π