DEV Community

Ugwuoke Adaeze
Ugwuoke Adaeze

Posted on • Edited on

A Beginner's Guide to Loops

Loops are one of the most important concepts to understand when learning programming. They are control flow statements that allow you to repeat a block of code multiple times, making your programs more efficient and less repetitive. They are tools that let your program repeat actions until a certain condition is met. Conditions typically return true or false. A loop will continue running until the defined condition returns false.

We’ll cover three types of loops in this article — for loop, while loop, and do-while loop — using simple, relatable examples, and explain when to use each.

Imagine you’re doing household chores: you wash one dish, then another, and you stop only when all the dishes are clean. That’s essentially a loop in action!

The For Loop
A for loop is a control flow statement that allows you to execute a block of code repeatedly. It's mostly used when you know in advance how many times you want to repeat the code, so you use the for loop to iterate over them one by one.

For loop syntax

for (initialization; condition; update) {
    // Code to execute in each iteration
}
Enter fullscreen mode Exit fullscreen mode
  • Initialization is executed once before the code block runs.
  • Condition defines the rule for the loop to run before and after each iteration.
  • Update happens after each iteration until the condition returns false, and the loop ends. This update can be an increment or a decrement.

Example: Delivering Packages
You have 5 packages to deliver. You need to:

Start with the first package.
Deliver each package in order.
Stop when all packages are delivered.

for (let i = 1; i <= 5; i++) {
    console.log("Delivering package number:", i);
}
Enter fullscreen mode Exit fullscreen mode

How It Works
let i = 1: Start with the first package (i is your counter, starting at 1).
i <= 5: Keep delivering while the number of packages (i) is less than or equal to 5.
i++: Move to the next package after delivering the current one.

When to Use a For Loop? When:

You know exactly how many times you need to repeat something.
Example: Printing numbers from 1 to 100, iterating through a list of items, or processing each item in an array.

The While Loop
A while loop is like an open-ended task. You keep doing something as long as a condition is true. You don’t know beforehand how many times you’ll repeat the action.

While loop syntax

while (condition) {
    // Code to execute as long as the condition is true
}
Enter fullscreen mode Exit fullscreen mode

Example: Filling a Glass with Water
You’re pouring water into a glass. You:

Start pouring.
Keep pouring while the glass isn’t full.
Stop when the glass is full.

let glassFull = false; // The glass starts empty

while (!glassFull) { // Keep pouring while the glass is not full
    console.log("Pouring water...");
    glassFull = true; // Assume the glass becomes full after pouring
}
Enter fullscreen mode Exit fullscreen mode

How It Works
glassFull = false: Start with an empty glass.
while (!glassFull): Condition Check... Is the glass is full? If not, continue pouring.
glassFull = true: After pouring, the glass becomes full, and the loop stops.

When to Use a While Loop? when:

You don’t know beforehand how many times you’ll repeat the action.

Example: Waiting for user input, processing data until a condition is met, or retrying an operation until it succeeds.

The Do-While Loop
A do-while loop is like a while loop, but with one key difference:
It always runs the code at least once, before checking if the condition is true, then it repeats the loop as long as the c.

Do-While loop syntax

do {
    // Code to execute at least once
} while (condition);
Enter fullscreen mode Exit fullscreen mode

Real-Life Example: Playing a ludo game
You roll a dice first
If you get a 6, you roll again until you don't.

let diceRoll;
do {
    diceRoll = Math.floor(Math.random() * 6) + 1; // Roll the dice (random number between 1 and 6)
    console.log("You rolled:", dice);
} while (diceRoll === 6); // Keep rolling if the number is less than 6
Enter fullscreen mode Exit fullscreen mode

How It Works
First Roll: The do part executes, rolling the dice.
Condition Check: The while part checks if the number is than 6. If true, roll again. If false, stop.

When to Use a Do-While Loop? Use when...

You need the code to run at least once before checking the condition.
Example: Asking for user input, retrying a failed operation, or initializing a task.

Key Differences Between For, While, and Do-While Loops

╔══════════════════════╦═══════════════════════╦════════════════════════╗
   For                       While              Do-While             
╠══════════════════════╬═══════════════════════╬════════════════════════╣
 When you know how      When the number of    When you must run the  
 many times to loop    repetitions is unknown code at least once     
╚══════════════════════╩═══════════════════════╩════════════════════════╝
Enter fullscreen mode Exit fullscreen mode

Which Loop Should You Use in Your Project?
When to use each loop in a real project:

For Loop in a Project

const products = [
  { name: "Product A", price: 10, quantity: 2 },
  { name: "Product B", price: 15, quantity: 3 },
  { name: "Product C", price: 20, quantity: 1 }
];

let totalCost = 0;

for (let i = 0; i < products.length; i++) {
  const product = products[i];
  totalCost += product.price * product.quantity;
}

console.log("Total cost:", totalCost);
Enter fullscreen mode Exit fullscreen mode

Explanation:

Initialization: We initialize a totalCost variable to 0.
Condition: Checks if the i is less than the length of the products.
Iteration: The for loop iterates over each product in the products array.
Calculation: For each product, we calculate the product's total cost by multiplying its price and quantity.
Accumulation: The calculated product cost is added to the totalCost variable.
Final Output: After processing all products, the final totalCost is printed to the console.

While Loop
Using the same code above, we'll convert it to a while loop.
If you’re waiting for user input:

const products = [
  { name: "Product A", price: 10, quantity: 2 },
  { name: "Product B", price: 15, quantity: 3 },
  { name: "Product C", price: 20, quantity: 1 }
];

let totalCost = 0;
let index = 0;

while (index < products.length) {
  const product = products[index];
  totalCost += product.price * product.quantity;
  index++;
}

console.log("Total cost:", totalCost);
Enter fullscreen mode Exit fullscreen mode

Do-While Loop in a Project
If you want to retry connecting to a server at least once:

let connected = false;

do {
    console.log("Trying to connect...");
    connected = true; // Assume the connection succeeds
} while (!connected);
Enter fullscreen mode Exit fullscreen mode

Happy Learning!

Top comments (0)