Lesson 2: The while Loop

Learning Objectives

By the end of this lesson, learners will:

  • Understand how and when to use a while loop
  • Learn the correct structure and logic behind a while loop
  • Know how to prevent infinite loops by updating the loop condition
  • Practice writing while loops for real-life logic like countdowns or validation

What Is a while Loop?

A while loop is used to repeat a block of code as long as a condition is true.

Unlike a for loop (which runs a set number of times), a while loop is best when:

  • You don’t know in advance how many times to run the loop
  • You want to repeat until something changes — like user input or a random value

Syntax of a while Loop

while (condition) {
  // code to run repeatedly
}
  • The condition is checked before each repetition.
  • If it’s true, the loop runs.
  • If it’s false, the loop stops.

Basic Example

let i = 1;

while (i <= 3) {
  console.log("Loop #" + i);
  i++; // don’t forget this!
}

Output:

Loop #1
Loop #2
Loop #3

This loop:

  1. Starts with i = 1
  2. Runs the block while i <= 3
  3. Increases i by 1 after each run
  4. Stops when i becomes 4 (condition is false)

Real-Life Use Case: Countdown

let countdown = 5;

while (countdown > 0) {
  console.log("Countdown: " + countdown);
  countdown--;
}
console.log("Liftoff!");

Output:

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Liftoff!

Infinite Loops – What to Avoid

A while loop must have a way to stop. If not, it will run forever and crash your program.

Example of an infinite loop:

let i = 1;

while (i <= 5) {
  console.log(i);
  // i++ is missing! Loop never ends
}

Always update your variable so the condition eventually becomes false.


while vs. for Loops – When to Use What?

Use CaseUse This Loop
You know how many timesfor loop
You don’t know when to stopwhile loop

📌 Examples:

  • while is great for waiting on user input
  • while is great for games where the player hasn’t quit yet
  • for is great for fixed iterations (e.g., 10 times)

Practice: Sum Until Limit

let total = 0;
let number = 1;

while (total < 20) {
  total += number;
  number++;
}
console.log("Final total: " + total);

This keeps adding numbers (1 + 2 + 3 + ...) until the total is 20 or more.