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 less repetitive, concise, and easier to maintain. They are tools that let your program repeat actions until a certain condition is met. Conditions 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. These loops basically do the same thing(repeating a block of code until the condition returns false), however, a type of loop may be preferred over another depending on the situation at hand. The syntax for most loops typically includes the following;
- Initialization: This is executed once before the code block runs.
- Condition: This defines the rule for the loop to run before and after each iteration. If the condition evaluates to true, the statement is executed, loop ends if false.
- Statement: This is the code to execute in each iteration. To execute multiple statements, use a block statement ({ }) to group them.
- Update: happens after each iteration until the condition returns false, and the loop ends. This update can be an increment or a decrement.
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 statement that allows you to execute a block of code repeatedly until the condition evaluates to false.
For loop syntax
for (initialization; condition; update) {
// Statement(s)
}
Example 1: 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);
}
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.
Example 2: Printing array items
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(`Fruit: ${fruits[i]}`);
}
// Logs "Fruit: apple", "Fruit: banana", "Fruit: cherry"
Example 3: Counting Down
for (let count = 10; count > 0; count--) {
console.log(`Countdown: ${count}`);
}
// Logs "Countdown: 10" to "Countdown: 1"
Example 4: Creating a Multiplication Table
for (let i = 1; i <= 5; i++) {
console.log(`2 x ${i} = ${2 * i}`);
}
// Logs "2 x 1 = 2" to "2 x 5 = 10"
The While Loop
You keep executing a statement as long as a condition remains true.
While loop syntax
while (condition) {
// Statement
update
}
Example 1: 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
}
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.
Example 2: Summing up Numbers
let num = 1;
let sum = 0;
while (num <= 10) {
sum += num;
num++;
}
console.log(`Sum: ${sum}`);
// Logs "Sum: 55"
Example 3: Evaluating User's Input
let password = "";
while (password.length < 8) {
password = prompt("Enter a password with at least 8 characters:");
}
console.log("Password accepted.");
Example 4: Calculating Total Cart Price
const cart = [
{ item: "Laptop", price: 1200 },
{ item: "Mouse", price: 25 },
{ item: "Keyboard", price: 75 },
];
let total = 0;
let i = 0;
for ( i < cart.length ) {
total += cart[i].price;
i++;
}
console.log(`Total cart price: #${total}`);
The Do 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 until the condition evaluates to false.
Do loop syntax
do {
// Statement
} while (condition);
Example 1: 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 ( the operation generates a random number between 1 and 6)
console.log(`You rolled a: , ${diceRoll}`);
} while (diceRoll === 6); // Keep rolling if the number is less than 6
How It Works
First Roll: The do part executes, rolling the dice.
Condition Check: The while part checks if the number is 6. If true, roll again. If false, stop.
Example 2: Showing Onboarding Steps
const steps = ["Step 1: Welcome", "Step 2: Set Up Profile", "Step 3: Complete Tutorial"];
let stepIndex = 0;
do {
console.log(steps[stepIndex]);
stepIndex++;
} while (stepIndex < steps.length);
Example 3: User Authentication Simulation
const correctPassword = "secure123";
let enteredPassword;
do {
enteredPassword = prompt("Enter your password:");
} while (enteredPassword !== correctPassword);
console.log("Welcome back!");
Example 4: Pagination (Loading Pages)
let currentPage = 1;
const totalPages = 5;
do {
console.log(`Loading page ${currentPage}...`);
currentPage++;
} while (currentPage <= totalPages);
console.log("All pages loaded.");
Converting Between Loops
The key to converting between loops is knowing where to place each part is placed in a loop's syntax; initialization, condition, update, and statement.
For Loop
All parts come in a bracket after the for statement
for (initialization; condition; update) {
// execution statement
}
While Loop
initialization; // Move initialization before the loop
while (condition) { // Condition comes right after the while statement
Execution Statement // inside the loop
update; // inside the loop, right after the statement
}
Do Loop
initialization; // move before the loop
do {
Execution Statement // inside the loop
update; // inside the loop
} while (condition); // condition is checked after the loop body
Example Conversion between loops
For loop
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);
Explanation:
Initialization: We initialize a totalCost variable to 0.
Condition: Checks if the i is less than the length of the products.
Update: The 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.
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);
Do Loop
Using the same lets convert to a Do loop.
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 i = 0;
do {
const product = products[i];
totalCost += product.price * product.quantity;
i++;
} while (i < products.length)
console.log("Total cost:", totalCost);
Happy Learning!
Top comments (0)