Video Lesson

Lesson Notes

Understanding break and continue in JavaScript for Loops

In this post, we’ll cover how to use the break and continue keywords inside a for loop to control loop execution.

Basic for Loop

1for (var i = 0; i < 10; i++) { 2 console.log(`Current value of i is: ${i}`); 3} 4console.log(`Final value of i is: ${i}`); 5// Uses `var` so `i` is accessible after the loop

Using continue

  • Purpose: Skip the rest of the current iteration and move to the next one.
1for (var i = 0; i < 10; i++) { 2 if (i >= 5) { 3 continue; // Skip logging when i is 5 or greater 4 } 5 console.log(i); 6} 7console.log(`Final value of i is: ${i}`); 8// Output: 0,1,2,3,4 then "Final value of i is: 10"

How It Works

  1. Evaluate if (i >= 5).
  2. When true, continue jumps back to the top, increments i, and skips console.log.
  3. Loop ends when i < 10 becomes false.

Using break

  • Purpose: Exit the loop entirely and move on to the next statement after the loop.
1for (var i = 0; i < 10; i++) { 2 if (i >= 5) { 3 break; // Stop loop when i reaches 5 4 } 5 console.log(i); 6} 7console.log(`Final value of i is: ${i}`); 8// Output: 0,1,2,3,4 then "Final value of i is: 5"

How It Works

  1. Evaluate if (i >= 5).
  2. When true, break immediately exits the loop.
  3. No further iterations occur.

Key Differences

  • continue
    • Skips to next iteration
    • Loop still runs until its condition is false
  • break
    • Exits loop immediately
    • No further iterations

Summary

  • Use continue to skip the rest of the current iteration.
  • Use break to stop the loop entirely.
  • Both help you add conditional control inside loops for cleaner, more efficient code.

AI Assistant

Sign In Required

Sign in and subscribe to use the AI assistant for instant help with your lessons.

Sign In

`break` and `continue` in JavaScript Loops

In this lesson, you'll use `break` and `continue` in JavaScript `for` loops, empowering you to control loop execution with precision. We'll cover how to efficiently skip iterations or exit loops entirely, enhancing your coding skills and streamlining your JavaScript programs.

5m 54s

Course Content

0 of 32 lessons completed
6. Promises, Async and Await
0 of 0 completed
7. The DOM
0 of 0 completed