Loops in JavaScript: for, while, do while

4/13/2025

#Loops in JavaScript: for, while, do while

Go Back

Loops in JavaScript: for, while, do...while Explained

Loops are a fundamental concept in programming that allow you to execute a block of code multiple times. JavaScript provides several types of loops to handle different situations.

In this tutorial, we’ll cover the most commonly used loop structures: for, while, and do...while.


#Loops in JavaScript: for, while, do while

1. for Loop

The for loop is used when the number of iterations is known beforehand.

✅ Syntax:

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

✅ Example:

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

This loop will run 5 times, printing the iteration number.


2. while Loop

The while loop is used when the number of iterations is not known in advance. It continues as long as the condition is true.

✅ Syntax:

while (condition) {
  // code to execute
}

✅ Example:

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

3. do...while Loop

The do...while loop is similar to the while loop, but it ensures the code block runs at least once, even if the condition is false.

✅ Syntax:

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

✅ Example:

let number = 1;
do {
  console.log("Number: " + number);
  number++;
} while (number <= 5);

4. Break and Continue

🔸 break

Used to exit the loop prematurely.

for (let i = 1; i <= 10; i++) {
  if (i === 6) break;
  console.log(i);
} // Outputs 1 to 5

🔸 continue

Skips the current iteration and continues with the next one.

for (let i = 1; i <= 5; i++) {
  if (i === 3) continue;
  console.log(i);
} // Outputs 1, 2, 4, 5

5. Best Practices

  • ✅ Use for when you know how many times to loop.

  • ✅ Use while or do...while when the loop should run based on a condition.

  • ✅ Avoid infinite loops by ensuring the condition eventually becomes false.

  • ✅ Use break and continue to manage loop flow carefully.


Final Thoughts

Loops are crucial for repeating tasks efficiently. By mastering for, while, and do...while loops in JavaScript, you’ll gain greater control over your code’s behavior and structure.

Practice different types of loops and experiment with nested loops and loop control statements to become more confident in your coding skills.

Table of content