learn2kode.in

JavaScript Loops (for, while, do…while)

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:

1. for Loop (Most Common & Recommended)

Use this loop when you know how many times you want to run the code.

Syntax
for (initialization; condition; increment) {
  // code to run
}
Example
for (let i = 1; i <= 5; i++) {
  console.log("Number: " + i);
}
Output
Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5
2. while Loop

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.

Syntax
while (condition) {
  // code to run
}
Example
let i = 1;

while (i <= 5) {
  console.log("Count: " + i);
  i++;
}
Output
Count: 1  
Count: 2  
Count: 3  
Count: 4  
Count: 5
3. do…while Loop

This loop runs at least once, even if the condition is false. The condition is checked after the code runs.

Syntax
do {
  // code to run
} while (condition);
Example
let i = 1;

do {
  console.log("Value: " + i);
  i++;
} while (i <= 5);
Output
Value: 1  
Value: 2  
Value: 3  
Value: 4  
Value: 5
Comparison Table

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