JavaScript Loops
Repeat tasks efficiently with loop constructs.
for/whilefor...ofbreak/continueTable of Contents
JavaScript Loops Tutorial (Complete Guide)
Loops let you repeat a block of code efficiently instead of writing it multiple times. They are essential for iterating arrays, processing data, and automating repetitive work.

1. for Loop (Most Common)
Use for when you know how many times the loop should run.
for (let i = 1; i <= 5; i++) {
console.log("Number:", i);
}Here, the loop starts at i = 1, runs until i <= 5, and increments each time.
2. while Loop (Condition-Based)
Use while when the number of iterations is not fixed.
let i = 1;
while (i <= 5) {
console.log("Number:", i);
i++;
}3. do...while Loop (Runs at Least Once)
This loop executes at least once, even if condition is false initially.
let i = 1;
do {
console.log("Number:", i);
i++;
} while (i <= 5);4. for...of Loop (Array Values)
Use for...of to loop through values in arrays or iterable objects.
let fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}5. for...in Loop (Object Keys)
Use for...in to loop through object properties.
let person = {
name: "John",
age: 25
};
for (let key in person) {
console.log(key + ": " + person[key]);
}7. Loop Control Statements
break (Stop Loop)
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i);
}
// Output: 1, 2continue (Skip Iteration)
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
// Output: 1, 2, 4, 58. Real-Life Example
let numbers = [10, 20, 30, 40];
let sum = 0;
for (let num of numbers) {
sum += num;
}
console.log("Total:", sum);9. Common Mistakes
- Infinite loop due to missing update step:
let i = 1;
while (i <= 5) {
console.log(i);
// missing i++
}- Using
for...infor arrays (not recommended). Usefor...offor array values.
10. When to Use What
- Use
forwhen you know the count. - Use
whilewhen condition controls execution. - Use
do...whilewhen at least one run is needed. - Use
for...offor arrays. - Use
for...infor objects.
Related Topics
Control Flow, Switch Statement, and Functions together cover most program flow and iteration patterns.