DEV Community

Ragul
Ragul

Posted on

JavaScript Loops

Have you ever found yourself writing the same line of code over and over again?

Imagine needing to log numbers from 1 to 100 or process a list of items. Writing 100 console.log() statements is not only exhausting—it breaks the core programming rule: DRY (Don't Repeat Yourself).

That’s where Loops come to the rescue!

In this guide, we'll break down the three fundamental loops in JavaScript:

  1. while Loop
  2. do...while Loop
  3. for Loop

Let’s dive into how each works, when to use them, and how to avoid the dreaded infinite loop!


1. The while Loop (Check First, Run Later)

The while loop evaluates a condition before executing the code block. If the condition is true, the code runs; if it's false, JavaScript skips it entirely.

Syntax

while (condition) {
  // Code to execute as long as condition is true
}
Enter fullscreen mode Exit fullscreen mode

Practical Example

let count = 1;

while (count <= 5) {
  console.log(`Count is: ${count}`);
  count++; // Don't forget to update your counter!
}
Enter fullscreen mode Exit fullscreen mode

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Enter fullscreen mode Exit fullscreen mode

How It Works Step-by-Step

  1. Initialize count = 1.
  2. Check if count <= 5 (1 <= 5 is true).
  3. Run the body → prints Count is: 1.
  4. Increment count to 2.
  5. Repeat until count becomes 6.
  6. Check count <= 5 (6 <= 5 is false) → Loop terminates!

Best Use Case: When you don't know the exact number of iterations in advance (e.g., polling an API until a status changes to "ready" or waiting for specific user input).


2. The do...while Loop (Run First, Check Later)

The do...while loop is very similar to the while loop, with one crucial difference: it is guaranteed to run at least once, even if the condition is false from the start.

Syntax

do {
  // Code executes first...
} while (condition); // ...then condition is checked!
Enter fullscreen mode Exit fullscreen mode

Example: Normal Execution

let attempts = 1;

do {
  console.log(`Attempt #${attempts}`);
  attempts++;
} while (attempts <= 3);
Enter fullscreen mode Exit fullscreen mode

Output:

Attempt #1
Attempt #2
Attempt #3
Enter fullscreen mode Exit fullscreen mode

What Happens When Condition Starts as False?

let score = 100;

do {
  console.log(`Current score: ${score}`);
} while (score < 50);
Enter fullscreen mode Exit fullscreen mode

Output:

Current score: 100
Enter fullscreen mode Exit fullscreen mode

Even though score < 50 is false, the code block still executed once before evaluating the condition!

Best Use Case: When an action must occur at least once regardless of conditions (e.g., prompting a user for input, rolling a die at least once, or performing an initial handshake attempt).


3. The for Loop (The All-in-One Powerhouse)

The for loop is the most commonly used loop in JavaScript. It neatly combines initialization, condition, and update/increment in a single, compact line.

Syntax

for (initialization; condition; update) {
  // Code to execute
}
Enter fullscreen mode Exit fullscreen mode
  • Initialization: Executes once before the loop starts (let i = 0).
  • Condition: Evaluated before every iteration (i < 5).
  • Update: Executes after every iteration (i++).

Practical Example

for (let i = 1; i <= 5; i++) {
  console.log(`Iteration: ${i}`);
}
Enter fullscreen mode Exit fullscreen mode

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Enter fullscreen mode Exit fullscreen mode

Real-World Example: Iterating Over an Array

const frameworks = ["React", "Vue", "Angular", "Svelte"];

for (let i = 0; i < frameworks.length; i++) {
  console.log(`${i + 1}. ${frameworks[i]}`);
}
Enter fullscreen mode Exit fullscreen mode

Output:

1. React
2. Vue
3. Angular
4. Svelte
Enter fullscreen mode Exit fullscreen mode

Best Use Case: When you know exactly how many times the loop should run (e.g., fixed counts, iterating arrays via indices).


Bonus: Loop Controls (break and continue)

Want more control inside your loops? Use these two keywords:

  1. break: Immediately exits the loop completely.
   for (let i = 1; i <= 10; i++) {
     if (i === 4) break; // Exits when i reaches 4
     console.log(i);
   }
   // Prints: 1, 2, 3
Enter fullscreen mode Exit fullscreen mode
  1. continue: Skips the current iteration and jumps straight to the next one.
   for (let i = 1; i <= 5; i++) {
     if (i === 3) continue; // Skips printing 3
     console.log(i);
   }
   // Prints: 1, 2, 4, 5
Enter fullscreen mode Exit fullscreen mode

Common Pitfall: The Infinite Loop

If your condition never becomes false, your loop will run forever and freeze/crash your browser or Node.js process.

// DANGER: Infinite Loop!
let x = 1;
while (x > 0) {
  console.log(x);
  x++; // x will always be greater than 0!
}
Enter fullscreen mode Exit fullscreen mode

Pro Tip: Always double-check your loop's exit condition and make sure your counter or state actually moves toward terminating!


Quick Summary & Comparison

Feature while Loop do...while Loop for Loop
Condition Check Before block executes After block executes Before each iteration
Minimum Runs 0 times 1 time 0 times
Best For Dynamic / unknown iterations Must run at least once Known iterations / array indexing
Syntax Style Separate init & update Separate init & update Compact (all-in-one header)

Top comments (0)