Loops in JavaScript – For, While, Do While, Break and Continue
Quick Answer: Loops repeat code while a condition allows it. JavaScript provides for, while and do...while loops. Use break to stop a loop and continue to skip the current round.
Imagine you manage a grocery shop with 1,000 products. How will you print every product name and price? Writing one statement for each product would take too much work. We need a better way to repeat the same task.
1. The Problem: Repeating Code Without Loops
Suppose Priya manages a grocery shop. She wants to print three product names. Without loops, she must repeat the same instruction.
Example 1: Printing Products Without a Loop
Purpose: Print three grocery product names manually.
const product1 = "Rice";
const product2 = "Milk";
const product3 = "Sugar";
console.log(product1);
console.log(product2);
console.log(product3);
Expected output
Rice Milk Sugar
This works, but it gets hard to manage as products increase.
- We repeat the same instruction many times.
- Adding products means adding more statements.
- Changing the printing logic requires several edits.
- Long repeated code becomes harder to review.
Now think about 1,000 products. Repeating every statement is not practical.
2. The Solution: Use a Loop
Loop = a way to repeat instructions. We store products in an array and process each item.
Example 2: Printing Products Using a for Loop
Purpose: Read each product from an array and print its name.
Prerequisite: JavaScript running in a browser console or Node.js 20+.
const products = ["Rice", "Milk", "Sugar"];
for (let index = 0; index < products.length; index++) {
console.log(products[index]);
}
Expected output
Rice Milk Sugar
The loop handles every product with one block of code. Adding another product does not need another console.log() statement.
3. How a for Loop Works
A for loop is useful when we know the iteration pattern. Iteration = one complete round of a loop.
The flow starts at index zero, checks the condition, prints a product, and updates the index.
The for loop has three important parts:
for (initialization; condition; update) {
// Repeated statements
}
- Initialization: Runs once before the loop starts.
- Condition: Checks whether another iteration can run.
- Update: Runs after each completed iteration.
- Body: Contains the statements repeated by the loop.
4. while Loop in JavaScript
A while loop repeats while its condition remains true. Use it when the number of iterations is not known beforehand.
For example, Priya may process grocery orders until the pending order count reaches zero.
Example 3: Processing Pending Orders
let pendingOrders = 3;
while (pendingOrders > 0) {
console.log("Processing order " + pendingOrders);
pendingOrders--;
}
console.log("All orders completed");
Expected output
Processing order 3 Processing order 2 Processing order 1 All orders completed
The condition is checked first. Processing stops when no pending orders remain.
Important points
- The condition is checked before every iteration.
- If the condition starts as false, the body never runs.
- Update the condition-related value inside the loop.
- Always make sure the loop can eventually finish.
5. do...while Loop in JavaScript
A do...while loop runs its body before checking the condition. It always runs at least once.
Imagine Priya prints the shop's closing summary. She wants one summary, even when no orders remain.
Example 4: Printing the Closing Summary
let pendingOrders = 0;
do {
console.log("Shop closing summary generated");
pendingOrders--;
} while (pendingOrders > 0);
Expected output
Shop closing summary generated
The summary runs first. The condition decides whether another summary is needed.
Remember: A while loop checks first. A do...while loop runs first. This is their main difference.
6. break Statement in JavaScript
break = stop the current loop immediately. Use it when the required item is found or processing must stop.
Suppose Priya searches for a product in the grocery list. She does not need to check later products after finding it.
Example 5: Stop Searching After Finding Milk
const products = ["Rice", "Milk", "Sugar", "Wheat"];
for (let index = 0; index < products.length; index++) {
if (products[index] === "Milk") {
console.log("Product found: " + products[index]);
break;
}
console.log("Checking: " + products[index]);
}
Expected output
Checking: Rice Product found: Milk
After finding Milk, JavaScript exits the loop. Sugar and Wheat are not checked.
7. continue Statement in JavaScript
continue = skip the current iteration. The loop then moves to its next iteration.
Priya wants to print available products only. She skips products with zero stock.
Example 6: Skip Products With No Stock
const products = [
{ name: "Rice", stock: 10 },
{ name: "Milk", stock: 0 },
{ name: "Sugar", stock: 5 }
];
for (const product of products) {
if (product.stock === 0) {
continue;
}
console.log(product.name + ": " + product.stock);
}
Expected output
Rice: 10 Sugar: 5
Milk is skipped because its stock is zero. The loop continues with Sugar.
8. break vs continue – Visual Difference
The continue path returns to the next product. The break path leaves the loop.
| Statement | What it does | Best use |
|---|---|---|
break |
Stops the current loop. | Stop after finding a product. |
continue |
Skips the current iteration. | Skip products with zero stock. |
9. for vs while vs do...while
| Loop | Condition check | Minimum runs | Use it when |
|---|---|---|---|
for |
Before each iteration | Zero | You have a clear iteration pattern. |
while |
Before each iteration | Zero | You repeat until a condition changes. |
do...while |
After each iteration | One | The task must run at least once. |
10. Step-by-Step Code Breakdown
Consider this common loop pattern:
const products = ["Rice", "Milk", "Sugar"];
for (let index = 0; index < products.length; index++) {
console.log(products[index]);
}
productsstores the product names in an array.let index = 0starts from the first array position.index < products.lengthchecks whether an item exists.products[index]reads the current product.index++moves to the next array position.
JavaScript arrays use zero-based indexing. The first position is zero, not one.
11. Common Loop Mistakes and Best Practices
Mistake 1: Forgetting to update the condition
A loop can run forever when its condition never changes.
let count = 1;
while (count <= 3) {
console.log(count);
count++;
}
Always update the value that controls the loop.
Mistake 2: Using the wrong comparison
Use < when iterating through array indexes. Using <= can access one position beyond the final index.
Mistake 3: Confusing break and continue
break exits the loop. continue skips only the current iteration.
Mistake 4: Changing the array length unexpectedly
Be careful when adding or removing array items during iteration. It can change which items the loop visits.
Mistake 5: Choosing a loop that hides the intention
Use for...of when you only need array values. Use a traditional for loop when you need the index.
Example 7: A Cleaner for...of Loop
const products = ["Rice", "Milk", "Sugar"];
for (const product of products) {
console.log(product);
}
Expected output
Rice Milk Sugar
12. How Loops Work in Interviews
Question 1: What is a loop in JavaScript?
What the interviewer expects: Explain repetition and the stopping condition.
Strong answer: A loop repeats a block of code while its condition allows it. JavaScript provides for, while and do...while loops. We choose one based on the task. We can also use break and continue to control execution.
Question 2: What is the difference between while and do...while?
Strong answer: A while loop checks its condition before running. A do...while loop checks after running. So, do...while always runs at least once.
Question 3: What is the difference between break and continue?
Strong answer: Break exits the current loop completely. Continue skips the current iteration and moves forward. For example, we can stop searching after finding Milk. We can skip products that have zero stock.
Question 4: Can a loop run forever?
Strong answer: Yes. A loop can run forever if its condition never becomes false. I check the update logic and exit conditions carefully.
13. Hands-On Practice
Beginner: Print Product Names
Create an array containing five grocery products. Use a for loop to print every product.
Expected result: All five product names appear in order.
Intermediate: Skip Out-of-Stock Products
Create products with name and stock properties. Use continue to skip zero-stock products.
Hint: Check product.stock === 0 before printing.
Advanced: Find a Product and Stop
Search an array for a product name. Print its position and stop searching after finding it.
Hint: Combine if and break.
Challenge: Process Orders Until Empty
Start with five pending orders. Use a while loop to process each order.
Expected result: Print each order count and finish at zero.
14. Frequently Asked Questions
Which loop is best in JavaScript?
There is no single best loop for every situation. Choose based on the task and required control.
Can we use break inside a while loop?
Yes. The break statement works inside for, while and do...while loops.
Can continue be used inside a for loop?
Yes. It skips the current iteration and continues with the next one.
Does do...while run when the condition is false?
Yes. It runs its body once before checking the condition.
Can we use break outside a loop?
No. A break statement must be inside a loop or switch statement.
15. Next Steps and Community
Try It Yourself: Build a small grocery product listing using different loops. Test each loop with empty and populated arrays.
Explore Further: Read the official MDN guide to JavaScript loops and iteration.
Share Your Knowledge: Share your solutions and discuss different loop choices. Help other learners understand the differences.
Keep practising. The right loop makes repeated tasks easier to manage.
Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.