← Back to blog

Learn JavaScript while and for loops in a car journey

Use a road trip story to understand while and for loops, plus how continue and break affect the flow in JavaScript.

The road trip setup

Imagine a car driving from one city to another. We care about three things:

  • Distance remaining (miles left to drive).
  • Fuel level (liters in the tank).
  • Driving conditions (weather, traffic, roadworks).

Loops are perfect because a journey repeats the same checks over and over until you reach the destination.

While loop: drive until you arrive

A while loop is ideal when you do not know how many times you will repeat a task. The car keeps moving while there is still distance to go.

Code
let distanceRemaining = 180;
let fuel = 24;
const fuelPerMile = 0.12;

while (distanceRemaining > 0 && fuel > 0) {
  distanceRemaining -= 10;
  fuel -= 10 * fuelPerMile;

  console.log(`Distance left: ${distanceRemaining} miles, fuel: ${fuel.toFixed(1)} L`);
}

The loop stops when either the distance reaches 0 or the fuel runs out but will run continuously until that point.

For loop: plan the trip in fixed stages

A for loop shines when you know exactly how many steps you want. Let’s say we split the trip into 6 planned legs of 30 miles each.

Code
let fuel = 24;
const fuelPerMile = 0.12;
const legDistance = 30;

for (let leg = 1; leg <= 6; leg += 1) {
  fuel -= legDistance * fuelPerMile;
  console.log(`Leg ${leg}: fuel left ${fuel.toFixed(1)} L`);
}

This is useful for scheduled checks, or a fixed number of instructions.

Continue: skip a leg because of traffic

Sometimes you want to skip part of the loop and move to the next iteration. That is what continue does.

In our road trip, imagine we decide to avoid a city center leg because there is heavy traffic. So we want to skip the fuel calculation for that leg.

Code
const legs = ['highway', 'city', 'highway', 'mountain', 'city', 'highway'];
let fuel = 24;
const fuelPerMile = 0.12;
const legDistance = 30;

for (let i = 0; i < legs.length; i += 1) {
  const segment = legs[i];

  if (segment === 'city') {
    console.log('Traffic jam detected. Taking a detour.');
    continue;
  }

  fuel -= legDistance * fuelPerMile;
  console.log(`${segment} leg complete. Fuel left ${fuel.toFixed(1)} L`);
}

Because of continue`*, the loop skips directly to the start of the next leg whenever there is a city traffic jam, skipping both cities in our legs array.

Break: stop the trip if conditions are unsafe

break ends the loop entirely. This is useful if something critical happens, like extreme weather or a fuel emergency.

Code
let distanceRemaining = 180;
let fuel = 24;
const fuelPerMile = 0.12;

while (distanceRemaining > 0 && fuel > 0) {
  const weather = Math.random() > 0.8 ? 'storm' : 'clear';

  if (weather === 'storm') {
    console.log('Storm warning. Ending the trip early.');
    break;
  }

  distanceRemaining -= 10;
  fuel -= 10 * fuelPerMile;
}

Whenever a storm randomly appears, the loop stops immediately, even if there is still distance remaining.

Putting it together

Here is a compact version showing distance, fuel, continue, and break in one loop:

Code
let distanceRemaining = 120;
let fuel = 18;
const fuelPerMile = 0.12;

while (distanceRemaining > 0 && fuel > 0) {
  const traffic = Math.random() > 0.7;
  const roadClosed = Math.random() > 0.95;

  if (roadClosed) {
    console.log('Road closed. Trip ends here.');
    break;
  }

  if (traffic) {
    console.log('Heavy traffic. Skipping this segment.');
    continue;
  }

  distanceRemaining -= 10;
  fuel -= 10 * fuelPerMile;
  console.log(`Driving... ${distanceRemaining} miles left.`);
}

Final takeaway

  • Use while loops when the number of repeats is unknown (drive until the final destination).
  • Use for loops when the repeats are counted (driving to planned legs).
  • Use continue to skip a step (taking a traffic detour).
  • Use break to end early (want to stop against specific conditions).

Loops are just journeys: repeat the checks, update the variables and stop when you have to.