1 Answers
📚 What is the 'continue' Statement?
In JavaScript, the continue statement is used inside loops (like for or while loops) to skip the rest of the current iteration and move on to the next iteration. It's like saying, "Okay, I'm not going to finish this part, let's just go to the next one!"
📜 A Little History
The continue statement has been a part of JavaScript since its early days. It's a fundamental control flow statement, designed to give programmers more control over how loops execute. It's found in many other programming languages too, showing how useful it is!
🔑 Key Principles
- ⏭️ Skipping Iterations: The main job of
continueis to skip the remaining code inside a loop for the current iteration. - 🔄 Loop Continues: It doesn't stop the loop entirely; it just moves to the next cycle.
- 📍 Placement Matters:
continueis always used inside a loop.
💻 Sample Code for Grade 8 Learners
Let's look at a simple example to see how continue works:
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) { // If i is even
continue; // Skip even numbers
}
console.log(i); // This will only print odd numbers
}
In this example, the loop goes from 1 to 10. When i is an even number (like 2, 4, 6, 8, 10), the continue statement is executed. This means the console.log(i) line is skipped, and the loop moves on to the next number. As a result, only the odd numbers (1, 3, 5, 7, 9) are printed.
💡 Real-World Examples
Imagine you're processing a list of student grades, and you want to calculate the average grade, but you want to ignore any grades that are below 50. You can use continue to skip those grades:
let grades = [80, 45, 90, 60, 35, 70];
let sum = 0;
let count = 0;
for (let i = 0; i < grades.length; i++) {
if (grades[i] < 50) {
continue; // Skip grades below 50
}
sum += grades[i];
count++;
}
let average = sum / count;
console.log("Average grade: " + average);
✍️ Practice Quiz
- ❓ What does the
continuestatement do in JavaScript? - 📝 Give an example of when you might use the
continuestatement in a loop. - 🤔 What will be the output of the following code?
for (let i = 0; i < 5; i++) { if (i === 3) { continue; } console.log(i); }
✅ 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 certain conditions, making your code more efficient and readable. Keep practicing with different examples, and you'll master it in no time!
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! 🚀