javascript


When writing code, you'll often find yourself needing to repeat actions — like printing numbers, processing items in a list, or retrying a failed operation. That’s where loops come in. JavaScript offers several loop types to handle repeated tasks. In this post, we'll explore the three most common ones: `for` loop `while` loop `do-while` loop

The `for` Loop The `for` loop is best when you know how many times you want to run a block of code.


for (initialization; condition; increment) {
  // code to run
}


for (let i = 1; i <= 5; i++) {
  console.log("Count:", i);
}


🔍 What happens here:

 `let i = 1` initializes the counter.
 `i <= 5` is the condition checked before each loop.
 `i++` increments `i` after each iteration.
 It logs numbers 1 to 5. 

The `while` Loop Use a `while` loop when you don’t know beforehand how many times the loop should run. It continues as long as a condition is true.


while (condition) {
  // code to run
}


let i = 1;
while (i <= 5) {
  console.log("Count:", i);
  i++;
}


This does the same as the `for` loop above, but with the loop control outside the loop declaration.

 The `do-while` Loop

A `do-while` loop is similar to a `while` loop, but with one key difference: the loop runs at least once, even if the condition is false.


do {
  // code to run
} while (condition);



let i = 1;
do {
  console.log("Count:", i);
  i++;
} while (i <= 5);
 

When to Use Each Loop?

| `for` When the number of iterations is known. `while` When the number of iterations is unknown and condition-based. `do-while` When you need the loop to run at least once regardless of the condition.