Loops
In real life, we repeat tasks all the time. We check notifications every day, send reminders to many users, or calculate totals for multiple items.
In JavaScript, loops help us repeat a block of code multiple times without writing it again and again.
What Is a Loop?
A loop allows JavaScript to execute the same code repeatedly as long as a condition is true.
Loops save time, reduce errors, and make code cleaner.
The for Loop
The for loop is commonly used when you know
how many times the code should run.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
This loop prints numbers from 1 to 5.
The while Loop
The while loop runs as long as the condition is true.
let count = 1;
while (count <= 3) {
console.log("Count:", count);
count++;
}
If the condition becomes false, the loop stops.
The do...while Loop
The do...while loop runs the code at least once,
even if the condition is false.
let number = 5;
do {
console.log(number);
number++;
} while (number < 5);
This behavior is useful when an action must run at least once.
Real-World Example
Imagine sending a message to multiple users:
let users = 5;
for (let i = 1; i <= users; i++) {
console.log("Message sent to user " + i);
}
Loops are widely used in notifications, reports, and data processing.
Common Beginner Mistakes
- Forgetting to update the loop counter
- Creating infinite loops
- Using the wrong loop type
Always ensure the loop condition eventually becomes false.
Thumb Rules
- Use
forwhen you know the number of iterations - Use
whilewhen the condition controls repetition - Avoid infinite loops unless intentionally needed
- Keep loop logic simple and readable
More on Loops Later
In this lesson, we covered the basic looping structures.
More advanced looping techniques are covered in later lessons.
- Looping through collections is explained in Lesson 11 (Arrays)
- Advanced control flow is discussed in later advanced lessons
What Comes Next?
Now that you know how to repeat actions, it’s time to organize code into reusable blocks.
In the next lesson, we will learn about functions.