*
Previous JavaScript-Conditionals JavaScript: Break & Continue Next

JavaScript Loops (for, while, do…while)

📘 JavaScript Loops (for, while, do…while)

Loops are the backbone of repetition in JavaScript. Also in any programming language. They let you run a block of code multiple times until a condition is met. Let’s go through the three main loops: for, while, and do…while.

1️⃣ for Loop

The for loop is used when you know how many times you want to run the code. It has 3 parts: initialization, condition, and increment/decrement.

// Print numbers 1 to 5
for (let i = 1; i <= 5; i++) {
  console.log(i);
}
// Output: 1 2 3 4 5
  

2️⃣ while Loop

The while loop runs as long as the condition is true. It’s useful when the number of iterations is not known in advance.

// Print numbers 1 to 5
let j = 1;
while (j <= 5) {
  console.log(j);
  j++;
}
// Output: 1 2 3 4 5
  

3️⃣ do…while Loop

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

// Print numbers 1 to 5
let k = 1;
do {
  console.log(k);
  k++;
} while (k <= 5);
// Output: 1 2 3 4 5
  

✅ Quick Recap

  • for → Best when you know the exact number of iterations.
  • while → Best when you don’t know how many times, but have a condition.
  • do…while → Always runs at least once, then checks the condition.
  • Always ensure the loop has a termination condition to avoid infinite loops.

📌 Mini Project: Sum of Numbers

// Calculate sum of numbers 1 to 5 using a for loop
let sum = 0;
for (let i = 1; i <= 5; i++) {
  sum += i;
}
console.log("Sum = " + sum); // Sum = 15
  

📘 Best Practices for Using Loops in JavaScript

  1. Choose the right loop type: Use for when the number of iterations is known, while or do…while when it depends on a condition.
  2. Avoid infinite loops: Ensure loop conditions will eventually become false.
    let i = 0;
    while(i < 5) {
      console.log(i);
      i++; // ensures termination
    }
  3. Minimize work inside the loop: Precompute values outside the loop if possible.
  4. Use descriptive variable names:
    for(let index = 0; index < items.length; index++) { ... }
  5. Break early if possible:
    for(let i = 0; i < arr.length; i++) {
      if(arr[i] === target) break;
    }
  6. Use continue wisely:
    for(let i = 0; i < arr.length; i++) {
      if(arr[i] === null) continue;
      console.log(arr[i]);
    }
  7. Consider array methods for iteration: forEach, map, filter, reduce.
  8. Avoid modifying loop counters inside the loop body: Keeps behavior predictable.
  9. Optimize nested loops: Minimize nesting to prevent performance issues.
  10. Keep loops readable: Break complex logic into separate functions.
Back to Index
Previous JavaScript-Conditionals JavaScript: Break & Continue Next
*
*