What Are Loops?
Loops allow you to repeat a block of code multiple times. Instead of writing the same code 10 times, you write it once and let the loop handle the repetition.
💡 Real-world analogy
Counting from 1 to 10 is a loop. Each time you say the next number, you're repeating the same action until you reach the end.
The for Loop
The most common loop. Use it when you know how many times you want to repeat something.
for (let i = 0; i < 5; i++) {
console.log("Count:", i);
}
// Output: 0, 1, 2, 3, 4
The while Loop
Use when you don't know how many times you'll need to repeat — the loop continues while a condition is true.
let count = 0;
while (count < 3) {
console.log("While count:", count);
count++;
}
The do-while Loop
Similar to while, but the code runs at least once before checking the condition.
let x = 5;
do {
console.log("Do-while:", x);
x++;
} while (x < 3);
// Runs once even though x is not less than 3
Looping Through Arrays
One of the most common uses of loops is to process each item in an array.
let fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
console.log("I like", fruits[i]);
}
Breaking and Continuing
break— exit the loop immediatelycontinue— skip the current iteration and move to the next
for (let i = 0; i < 10; i++) {
if (i === 5) break; // stops at 5
if (i % 2 === 0) continue; // skips even numbers
console.log(i); // 1, 3
}
Common Mistakes
- Infinite loops — forgetting to increment the counter or update the condition
- Off-by-one errors — using
<=instead of<or vice versa - Modifying the array while iterating over it
Quick Quiz
1. How many times does this loop run?
for (let i = 0; i < 3; i++) { }
2. Which loop runs the code at least once?
3. What does break do in a loop?
Summary
forloops: use when you know the number of iterationswhileloops: use when you don't know the number of iterationsdo-whileloops: use when the code must run at least oncebreakexits a loop;continueskips to the next iteration- Always update the loop condition to avoid infinite loops
