Loops & Control Flow

🟨 JavaScript Lesson 6 Beginner

Loops repeat code blocks as long as a condition is satisfied. JavaScript supports standard for loops, while loops, do-while loops, and collection-specific loop variants.

1 Loop Structures: for, while, and do-while

Selecting appropriate iteration flows depends on execution requirements:

  • for: Best for iterating over fixed numeric ranges.
  • while: Evaluates conditions before checking execution blocks.
  • do-while: Executes execution blocks first, and then evaluates conditions.
2 Loop Control Tracing

Let's run a program iterating loops, checking break constraints, and skipping iterations via continue:

JavaScript — Loops ▶ Run Code
console.log("For iteration:");
for (let i = 1; i <= 5; i++) {
    console.log(i);
}

// Flow control with break/continue
console.log("While sequence (skipping 3, breaking at 6):");
let count = 1;
while (count <= 10) {
    if (count === 3) {
        count++;
        continue; // Skip the rest of this loop iteration
    }
    if (count === 6) {
        break; // Exit the loop entirely
    }
    console.log(count);
    count++;
}
3 Code Challenge
Challenge: Write a loop that sums all even numbers between 1 and 20. Skip the number 12 using the `continue` keyword, and print the computed sum at the end.