3.3 Module 3 · Decisions & Loops

Loops

Automate repetitive work with for, while, and do...while — and control the flow mid-loop with break and continue.

1

Definition

Loops in JavaScript execute a block of code repeatedly as long as a specified condition remains true. They automate repetitive tasks and eliminate code duplication — instead of writing console.log(1) through console.log(100), one loop handles all of it.

JavaScript provides three loop types — for, while, and do...while — plus break and continue to control what happens mid-loop.

2

Simple Way

Instead of writing the same code again and again, loops say: "Do this work multiple times until the condition fails."

for When you know exactly how many times to repeat — "loop 10 times"
while When you repeat until a condition changes"keep going while logged in"
do...while Run the code at least once, then check the condition
break Exit the loop immediately — stop everything now
continue Skip the current iteration — jump to the next one
3

Code Examples

Example 1 — for Loop
// Structure: for (initialise; condition; update)
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

// Count down
for (let i = 5; i >= 1; i--) {
  console.log(i);
}
Output
Click ▶ Run to execute
Explanation
  • Initialise (let i = 1) — sets the counter before the loop starts
  • Condition (i <= 5) — checked before each iteration; loop stops when false
  • Update (i++) — runs after each iteration to move the counter forward
Example 2 — while Loop
let i = 1;

while (i <= 3) {
  console.log("Round " + i);
  i++; // must update — otherwise infinite loop!
}

// while: condition checked BEFORE each run
// if false from the start, the body never runs
let count = 10;
while (count < 5) {
  console.log("This never prints");
  count++;
}
console.log("Loop skipped — condition was false from start");
Output
Click ▶ Run to execute
Explanation
  • The condition is evaluated before each iteration — if false at the start, the body never runs
  • Always update the variable inside the loop or it will run forever
  • Use while when the number of iterations is not known in advance
Example 3 — do...while Loop
let i = 1;

do {
  console.log("Run " + i);
  i++;
} while (i <= 3);

// Key difference: runs at least ONCE even if condition is false
let x = 100;
do {
  console.log("Runs once even though x > 5");
  x++;
} while (x < 5);
Output
Click ▶ Run to execute
Explanation
  • The body runs first, then the condition is checked — guarantees at least one execution
  • Common use case: asking a user to input data until they provide a valid value
  • Less common than for and while, but essential when the first run must always happen
Example 4 — break & continue
// continue — skip current iteration, keep going
for (let i = 1; i <= 5; i++) {
  if (i === 3) continue; // skip 3
  console.log(i);
}
// Output: 1, 2, 4, 5

// break — exit the loop entirely
for (let i = 1; i <= 10; i++) {
  if (i === 4) break; // stop at 4
  console.log(i);
}
// Output: 1, 2, 3
Output
Click ▶ Run — notice what's missing!
Explanation
  • continue skips the rest of the current iteration and jumps straight to the next one
  • break exits the loop immediately — no further iterations run
  • Both work inside for, while, and do...while
Example 5 — Looping Over an Array
let fruits = ["Apple", "Banana", "Mango", "Grapes"];

// Classic for loop with index
for (let i = 0; i < fruits.length; i++) {
  console.log(i + ": " + fruits[i]);
}

// Modern for...of — cleaner when index not needed
for (let fruit of fruits) {
  console.log(fruit.toUpperCase());
}
Output
Click ▶ Run to execute
Explanation
  • The classic for loop with array.length is the most universal way to iterate an array
  • for...of gives you each element directly — use it when you don't need the index
  • Always use i < array.length (not <=) — the last valid index is length - 1
4

Real-Life Example

Think of a washing machine — its cycle maps perfectly to loop concepts:

for
A 5-cycle setting — runs a fixed number of wash cycles
while
Washes until the timer reaches zero — condition-based
do...while
Always does one rinse first, then checks if more are needed
break
Emergency stop button — halts the machine immediately
continue
Skip the delicate cycle — jump straight to the next setting
for...of
Process each item in the laundry bag one at a time
5

HTML + JavaScript Example

Click ▶ Preview, enter a range, and watch a loop generate every number — with even numbers highlighted in yellow.

Live in Browser — Number Printer with Loop
<!DOCTYPE html>
<html>
<head><title>Loops Demo</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>Print Numbers</h2>

  <label>From:
    <input id="from" type="number" value="1"
      style="width:70px;padding:6px 10px;border:1px solid #ccc;
             border-radius:6px;font-size:1rem;margin:0 8px">
  </label>
  <label>To:
    <input id="to" type="number" value="10"
      style="width:70px;padding:6px 10px;border:1px solid #ccc;
             border-radius:6px;font-size:1rem;margin:0 8px">
  </label>
  <button onclick="printNums()"
    style="padding:8px 18px;background:#f7df1e;border:none;border-radius:6px;
           cursor:pointer;font-weight:700;font-size:1rem">
    Show
  </button>

  <div id="output"
    style="margin-top:16px;display:flex;flex-wrap:wrap;gap:8px">
  </div>

  <script>
    function printNums() {
      let from = Number(document.getElementById("from").value);
      let to   = Number(document.getElementById("to").value);
      let out  = document.getElementById("output");

      if (from > to || to - from > 200) {
        out.innerHTML = "<b style='color:red'>Enter a valid range (max 200 numbers).</b>";
        return;
      }

      let html = "";
      for (let i = from; i <= to; i++) {
        let isEven = i % 2 === 0;
        html += `<span style="display:inline-block;width:38px;height:38px;
          line-height:38px;text-align:center;border-radius:8px;font-weight:600;
          background:${isEven ? '#f7df1e' : '#e2e8f0'};
          color:${isEven ? '#111' : '#444'}">${i}</span>`;
      }

      out.innerHTML = html;
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Print 1 to 10
Starter code
// Use a for loop to print 1 through 10
for (let i = 1; i <= 10; i++) {
  // your code here
}
  • Print each number using console.log(i)
  • Modify the loop to count down from 10 to 1 instead
  • Calculate and print the sum of all numbers 1–10 inside the loop
Medium Task 2 — Even numbers 1 to 20
Starter code
for (let i = 1; i <= 20; i++) {
  // print only even numbers
}
  • Use i % 2 === 0 to check if a number is even — if not, continue to skip it
  • Print each even number with a label — e.g. "Even: 2"
  • Count how many even numbers were printed and log the total at the end
7

MCQs

Q1
How many times will this loop run?
for (let i = 1; i <= 3; i++) {
  console.log(i);
}
Output
Run it to verify
  • A 2
  • B 3
  • C 4
  • D 1
💡 B is correct. The loop starts at i = 1 and runs while i <= 3 — that's iterations for 1, 2, and 3. When i becomes 4, the condition is false and the loop stops.
Q2
Which loop always executes its body at least once?
let x = 100;

do {
  console.log("Ran once!");
  x++;
} while (x < 5);
Output
Run it to verify
  • A for
  • B while
  • C do...while
  • D for...of
💡 C is correct. do...while runs its body first and checks the condition after. Even though x = 100 fails x < 5 immediately, the body still executes once.
Q3
What does break do inside a loop?
for (let i = 1; i <= 5; i++) {
  if (i === 3) break;
  console.log(i);
}
Output
Run it to verify
  • A Skips the current iteration and continues
  • B Exits the loop immediately
  • C Restarts the loop from the beginning
  • D Throws an error
💡 B is correct. break exits the loop immediately — no further iterations run. Here, 1 and 2 print but when i === 3 the loop stops entirely. continue would only skip 3 and carry on to 4 and 5.
8

Pro Tips & Extra Knowledge

  • 01

    Choose the right loop for the job — matching the loop to the situation makes your intent clear:

    Which loop when?
    // for — known count
    for (let i = 0; i < 5; i++) console.log("Step", i);
    
    // while — unknown count (keep going until condition changes)
    let attempts = 0;
    while (attempts < 3) {
      console.log("Attempt", attempts + 1);
      attempts++;
    }
    
    // for...of — iterate array values cleanly
    let names = ["Aman", "Priya", "Raj"];
    for (let name of names) console.log("Hello,", name);
    Output
    Click ▶ Run to execute
  • 02

    Always avoid infinite loops — if the condition never becomes false, the browser will freeze. Always ensure your loop counter updates:

    Safe while loop pattern
    // ✗ Dangerous — i never changes, runs forever
    // while (i <= 5) { console.log(i); }  // commented out to be safe
    
    // ✓ Safe — i increments every iteration
    let i = 1;
    while (i <= 5) {
      console.log(i);
      i++; // critical — this ends the loop
    }
    Output
    Click ▶ Run to execute
  • 03

    Use continue to write filter logic inside loops — it's often cleaner than nesting an if block around everything:

    continue as a filter
    // Print only numbers divisible by 3 in range 1–15
    for (let i = 1; i <= 15; i++) {
      if (i % 3 !== 0) continue; // skip non-multiples of 3
      console.log(i); // only 3, 6, 9, 12, 15 reach here
    }
    Output
    Click ▶ Run to execute
  • 04

    Use break with a search pattern — exit as soon as you find what you're looking for instead of running unnecessary iterations:

    break to stop early on find
    let scores = [72, 88, 55, 95, 61];
    let target = 95;
    let found  = false;
    
    for (let i = 0; i < scores.length; i++) {
      if (scores[i] === target) {
        console.log("Found " + target + " at index " + i);
        found = true;
        break; // no point checking the rest
      }
    }
    
    if (!found) console.log("Not found");
    Output
    Click ▶ Run to execute
Mini Challenge

continue skips certain numbers — predict exactly which numbers will print before running.

What does this print?
for (let i = 1; i <= 5; i++) {
  if (i % 2 === 0) continue;
  console.log(i);
}
Output
Think first, then run!
Step-by-Step Explanation
// Loop runs for i = 1, 2, 3, 4, 5

// i = 1: 1 % 2 = 1 (not 0) → condition false → continue NOT triggered
//        console.log(1) → prints 1

// i = 2: 2 % 2 = 0 → condition true → continue triggered
//        Rest of body skipped → 2 is NOT printed

// i = 3: 3 % 2 = 1 → condition false → continue NOT triggered
//        console.log(3) → prints 3

// i = 4: 4 % 2 = 0 → condition true → continue triggered
//        4 is NOT printed

// i = 5: 5 % 2 = 1 → condition false → continue NOT triggered
//        console.log(5) → prints 5

// Final output:
//   1
//   3
//   5   ← only the ODD numbers

// Key takeaway:
//   i % 2 === 0 is true for EVEN numbers (2, 4)
//   continue skips the rest of the iteration for those numbers
//   So only ODD numbers (1, 3, 5) reach console.log