Loops in JavaScript allow you to repeat a block of code multiple times. They are used when you want to run the same task again and again without writing repetitive code. JavaScript provides three main types of loops:
Use this loop when you know how many times you want to run the code.
for (initialization; condition; increment) {
// code to run
}
for (let i = 1; i <= 5; i++) {
console.log("Number: " + i);
}
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Use this loop when you do not know the number of iterations ahead of time. The loop continues as long as the condition is true.
while (condition) {
// code to run
}
let i = 1;
while (i <= 5) {
console.log("Count: " + i);
i++;
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
This loop runs at least once, even if the condition is false. The condition is checked after the code runs.
do {
// code to run
} while (condition);
let i = 1;
do {
console.log("Value: " + i);
i++;
} while (i <= 5);
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
Here is a simple table comparing all three:
| Loop Type | When to Use | Runs At Least Once? |
|---|---|---|
for |
When the number of iterations is known | No |
while |
When condition-based looping is needed | No |
do...while |
When you need the code to run at least once | Yes |