CodingNic

Control Flow

Loops

Control Flow 20 min read

Loops

Objectives

By the end of this chapter, you should be able to:

  • Write a for loop and explain all three of its parts
  • Write a while loop
  • Write a do...while loop, and explain when it behaves differently from while

💡 Why this matters: Programs constantly need to repeat work: print every number in a range, keep asking for input until it’s valid, process one item after another. Loops let you write the repeated step once instead of copying it by hand.

The for Loop

A for loop is built for repeating something a known number of times. It has three parts, separated by semicolons, all sitting in the parentheses:

javascript
for (let i = 1; i <= 5; i++) {
  console.log(i);
}
// 1
// 2
// 3
// 4
// 5

Each part does a specific job:

  1. Initializer (let i = 1): runs once, before the loop starts. It usually declares a counter variable.
  2. Condition (i <= 5): checked before every iteration. As long as it’s true, the loop body runs. As soon as it’s false, the loop stops.
  3. Increment (i++): runs after every iteration, right before the condition is checked again. i++ is shorthand for i = i + 1.

Tracing through the example: i starts at 1. The condition 1 <= 5 is true, so the body runs and logs 1. Then i++ makes i become 2. The condition 2 <= 5 is still true, so it logs 2. This keeps going until i becomes 6, where 6 <= 5 is false, and the loop stops without printing 6.

You can count down just as easily by changing the direction:

javascript
for (let i = 5; i >= 1; i--) {
  console.log(i);
}
// 5
// 4
// 3
// 2
// 1

The while Loop

A while loop only has a condition. It keeps running its body as long as that condition stays true. You’re responsible for making sure something inside the loop eventually makes the condition false, otherwise it never stops.

javascript
let count = 1;

while (count <= 5) {
  console.log(count);
  count++;
}
// 1
// 2
// 3
// 4
// 5

This produces the same output as the first for loop. Use while when you don’t know in advance exactly how many times you’ll loop, for example, repeating something until a value crosses a threshold:

javascript
let savings = 100;
let years = 0;

while (savings < 200) {
  savings = savings * 1.1;
  years++;
}

console.log(years);
// 8

Here there’s no fixed count going in. The loop keeps doubling interest onto savings until it finally passes 200, however many years that takes.

The do...while Loop: Run the Body at Least Once

while checks its condition before running the body, so if the condition starts out false, the body never runs at all:

javascript
let stock = 0;

while (stock > 0) {
  console.log("Selling one item.");
  stock--;
}
console.log("Done.");
// Done.

stock is 0, so stock > 0 is false from the very first check, and "Selling one item." never prints.

A do...while loop checks its condition after running the body, so the body always runs at least once, no matter what:

javascript
let stock = 0;

do {
  console.log("Selling one item.");
  stock--;
} while (stock > 0);
console.log("Done.");
// Selling one item.
// Done.

Same starting value, same condition, but a different result: "Selling one item." prints exactly once here, because do...while runs the body first and only checks stock > 0 afterward. That single comparison, body-first versus condition-first, is the entire difference between the two loops, and it’s exactly why the two examples above print different things from the same starting state.

Reach for do...while specifically when the task must happen at least once before you can even check whether it should repeat. A countdown announcement is a good example: even a countdown that starts at 0 still needs to announce itself once before checking whether to count further.

javascript
let count = 0;

do {
  console.log(count);
  count--;
} while (count > 0);
// 0

With a plain while (count > 0), this would print nothing at all, because count starts at 0 and 0 > 0 is false immediately. The do...while guarantees that first announcement happens regardless.

Try It

  1. Write a for loop that logs the numbers 10 down to 1.
  2. Write a while loop that starts a variable total at 0 and a variable n at 1, adds n to total and increments n each time, stopping once total is greater than 20. Log the final total.
  3. Write two loops on a variable tickets set to 0: one while (tickets > 0) and one do...while (tickets > 0), each just logging "Ticket sold" and decrementing tickets. Confirm the while loop prints nothing and the do...while loop prints once.

Recap

  • for (initializer; condition; increment) is best when you know how many times to repeat.
  • while (condition) checks before each run of the body, so the body might never run.
  • do...while checks after each run of the body, so the body always runs at least once, useful when the first run has to happen before you can decide whether to repeat.

Next lesson: controlling a loop mid-run with break and continue, and nesting loops inside one another.