13.5 Break and Continue in Loops (10 mins)
Introduction to
breakandcontinueStatements:Break: Exits a loop completely, stopping its execution.
Use case: When you want to terminate the loop early, such as when a certain condition is met.
Example:
for (let i = 1; i <= 10; i++) { if (i === 5) { break; // Exit the loop when i equals 5 } console.log(i); // Outputs: 1, 2, 3, 4 }
Continue: Skips the current iteration and moves to the next iteration of the loop.
Use case: When you want to skip certain values or conditions, but keep the loop running.
Example:
for (let i = 1; i <= 5; i++) { if (i === 3) { continue; // Skip the current iteration when i equals 3 } console.log(i); // Outputs: 1, 2, 4, 5 (skips 3) }
How
breakandcontinueWork in Loops:Break: Stops the loop entirely and moves execution to the next part of the program.
Continue: Skips the rest of the code in the current loop iteration but continues with the next iteration.
When to Use
breakandcontinue:Break: Use when you need to stop a loop once a certain condition is met (e.g., finding a specific value in an array).
Continue: Use when you need to skip over certain elements in the loop (e.g., filtering out invalid inputs).
Student Activity (10 mins):
Objective: Incorporate break and continue statements into the previous loops to control the flow of iteration.
Step-by-Step Activity:
Modify the Previous Loops to Include
breakandcontinue:Instructions:
Open your previous HTML file (
loops_activity.html) and update the script to includebreakandcontinuestatements.
Example Code:
Run the file in a browser:
Open the HTML file in a browser and use Developer Tools (F12 or right-click and select Inspect > Console) to view how
breakandcontinuestatements affect the loop’s behavior.
Challenge:
Write a Loop to Find the First Number Divisible by Both 3 and 5:
Use the
breakstatement to exit the loop once a number divisible by both 3 and 5 is found.Example:
Write a Loop to Skip All Multiples of 4:
Use the
continuestatement to skip numbers divisible by 4.Example:
Activity Follow-up Questions:
How does the
breakstatement impact the flow of a loop compared tocontinue?Can you think of a real-world example where you would want to use
breakto stop a loop early?In what scenarios would you use
continueto skip certain iterations while still completing the loop?
Expected Outcome:
Students will:
Understand how to control loop flow using
breakto stop execution early andcontinueto skip specific iterations.Apply these concepts to modify existing loops and solve real-world problems that require breaking or skipping certain conditions.
Last updated