Javascript For While And Do While Loops Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of JavaScript for, while, and do while Loops

JavaScript for, while, and do while Loops

1. For Loop

The for loop is used to execute a block of code a specific number of times. It's particularly useful when you know in advance how many times the loop should run.

Syntax:

for (initialization; condition; increment) {
  // Code to be executed
}

Components:

  • Initialization: Sets the starting point of the loop, often initializing a counter variable. It is executed only once.
  • Condition: A boolean expression checked before every loop iteration. If evaluates to true, the loop continues; otherwise, it stops.
  • Increment: Updates the loop counter after each iteration. This step is crucial to eventually break the loop.

Example:

for (let i = 0; i < 5; i++) {
  console.log("Iteration number: " + i);
}
// Output: 
// Iteration number: 0
// Iteration number: 1
// Iteration number: 2
// Iteration number: 3
// Iteration number: 4

Important Information:

  • Can be used with arrays and objects, especially when combined with .length.
  • Can have more than one initialization and increment expression (use commas to separate them).
  • You can omit any of the three components, but avoid omitting the condition to prevent infinite loops.
  • Nested for loops can be used for tasks requiring multi-dimensional iteration.

2. While Loop

The while loop executes a block of code as long as a specified condition evaluates to true. This loop type is unsuitable when you need to execute a loop a set number of times, but it's perfect when the loop count is not predetermined.

Syntax:

while (condition) {
  // Code to be executed
}

Example:

let count = 0;
while (count < 3) {
  console.log("Count is: " + count);
  count++;
}
// Output: 
// Count is: 0
// Count is: 1
// Count is: 2

Important Information:

  • The loop condition is checked before each iteration.
  • Careful with infinite loops which occur when the condition never evaluates to false.
  • Ideal for situations where the number of iterations is not initially known but can be determined dynamically.

3. Do While Loop

The do while loop is similar to the while loop, but there is a key difference: it guarantees the loop will run at least once regardless of the condition.

Syntax:

do {
  // Code to be executed
} while (condition);

Example:

let x = 5;
do {
  console.log(x);
  x++;
} while (x < 2);
// Output: 
// 5

Important Information:

  • The loop body executes before the condition is tested.
  • This loop is useful when the block of code must execute at least once, such as user prompts where the validation checks occur after the input.
  • It’s generally less commonly used compared to for and while loops.

Summary

  • For Loop: Best when the number of iterations is known and finite.
  • While Loop: Suitable when the number of iterations depends on a condition evaluated before execution.
  • Do While Loop: Ensures the loop body executes at least once, useful for scenarios where post-execution condition checks are necessary.

Conclusion

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement JavaScript for, while, and do while Loops

For Loop

The for loop is used when you know in advance how many times the statement should be executed.

Example: Print numbers from 1 to 5

// Step-by-step explanation:

// Initialize a variable i to 1. This is our starting point.
// Check if i is less than or equal to 5. If true, execute the loop body.
// After each iteration of the loop, increment i by 1 using i++.

for (let i = 1; i <= 5; i++) {
    console.log(i); // This line prints the current value of i
}

// Output:
// 1
// 2
// 3
// 4
// 5

While Loop

The while loop executes its statements as long as a specified condition evaluates to true.

Example: Print numbers from 1 to 5

// Step-by-step explanation:

// Initialize a variable i to 1. This is our starting point.
// Use a while loop that checks if i is less than or equal to 5.
// If the condition is true, execute the loop body.
// Inside the loop body, use console.log(i) to print the current value of i.
// Increment i by 1 after each iteration using i++.

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

// Output:
// 1
// 2
// 3
// 4
// 5

Do While Loop

The do...while loop is similar to the while loop, but it guarantees that the loop body will execute at least once because the condition is evaluated after executing the statement.

Example: Print numbers from 1 to 5

// Step-by-step explanation:

// Initialize a variable i to 1. This is our starting point.
// Use a do...while loop that executes the loop body first, then checks the condition.
// Inside the loop body, use console.log(i) to print the current value of i.
// Increment i by 1 after each iteration using i++.
// The condition i <= 5 is checked after the loop body has been executed.
// If the condition is true, repeat the loop. If false, exit the loop.

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

// Output:
// 1
// 2
// 3
// 4
// 5

Practical Example: Sum of Numbers

Let's create a simple program to calculate the sum of numbers from 1 to 10 using each of the three loops.

Using For Loop

// Initialize sum to 0
let sum = 0;

for (let i = 1; i <= 10; i++) {
    sum += i; // Add current number to sum
}

console.log("Sum of numbers from 1 to 10 is:", sum);

// Output:
// Sum of numbers from 1 to 10 is: 55

Using While Loop

// Initialize sum to 0
let sum = 0;
let i = 1;

while (i <= 10) {
    sum += i; // Add current number to sum
    i++;
}

console.log("Sum of numbers from 1 to 10 is:", sum);

// Output:
// Sum of numbers from 1 to 10 is: 55

Using Do While Loop

// Initialize sum to 0
let sum = 0;
let i = 1;

do {
    sum += i; // Add current number to sum
    i++;
} while (i <= 10);

console.log("Sum of numbers from 1 to 10 is:", sum);

// Output:
// Sum of numbers from 1 to 10 is: 55

Infinite Loops

Warning: Be careful not to create an infinite loop. Below is an example of an infinite loop scenario that should be avoided in practice.

Infinite For Loop

// Incorrect example of an infinite for loop

for (let i = 1; ; i++) {
    console.log(i);
}
// This loop will run indefinitely because there is no terminating condition.

Incorrect While Loop

// Incorrect example of an infinite while loop

let i = 1;
while (true) {
    console.log(i);
    // Without i++ this loop will run indefinitely.
}

Incorrect Do While Loop

// Incorrect example of an infinite do...while loop

let i = 1;
do {
    console.log(i);
    // Without i++ this loop will run indefinitely.
} while (true);

Always ensure that your loop has a mechanism to terminate, otherwise, the browser or any running environment might crash.

Top 10 Interview Questions & Answers on JavaScript for, while, and do while Loops

1. What are the differences between for, while, and do...while loops in JavaScript?

  • For Loop: Used when the number of iterations is known beforehand.

    for (let i = 0; i < 10; i++) {
        console.log(i);
    }
    
  • While Loop: Executes as long as the provided condition evaluates to true. Unknown number of iterations.

    let i = 0;
    while (i < 10) {
        console.log(i);
        i++;
    }
    
  • Do...While Loop: Similar to the while loop, but it guarantees at least one execution even if the condition is false initially.

    let i = 0;
    do {
        console.log(i);
        i++;
    } while (i < 10);
    

2. Can you use a for loop to iterate over an object?

In JavaScript, objects are not iterable in the traditional sense like arrays. However, you can use a for...in loop to iterate over the keys of an object:

const obj = {a: 1, b: 2, c: 3};

for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(key + ' : ' + obj[key]);
    }
}

This will log:

a : 1
b : 2
c : 3

3. How do you break out of a while loop?

Use the break statement to exit a while loop prematurely:

let i = 0;
while (i < 10) {
    if (i === 5) break;
    console.log(i++);
}
// 0 to 4 will be logged, then the loop breaks when i equals 5.

4. How does a do...while loop differ from a while loop?

The main difference is that with a do...while loop, the block of code inside the loop runs at least once before the condition is evaluated:

let i = 0;

do {
    console.log(i);
    i++;
} while (i < 5);
// Logs 0 through 4.

// In contrast, the following while loop does not execute at all.
let j = 5;
while (j < 5) {
    console.log(j);
    j++;
}

5. Can you skip an iteration in a loop?

Yes, using the continue statement in any type of loop skips the rest of the current iteration and proceeds to the next iteration:

for (let i = 0; i < 10; i++) {
    if (i % 2 === 0) continue; // Skip even numbers
    console.log(i);             // Logs only odd numbers
}

6. When should I use a for loop versus a while loop?

  • Use for loops when the number of iterations is predetermined and you need precise control over initialization and step processes.
  • Use while loops when the number of iterations depends on dynamic conditions which may or may not be met during runtime.

7. Is it possible to have an infinite loop in JavaScript?

Yes, an infinite loop occurs when the loop condition never becomes false. Both while and do...while can create infinite loops:

while (true) {
    console.log('This is an infinite loop');
}

// Or using do...while
let i = 0;
do {
    console.log('This is also an infinite loop');
} while (true);

To avoid an infinite loop, ensure that there's a proper exit condition within the loop body.

8. Can loops handle asynchronous operations in JavaScript?

JavaScript loops themselves aren't designed to handle asynchronous operations directly. If you want to perform an operation multiple times asynchronously, you might need to use functions like Array.prototype.forEach, or recursion, especially with promise chains:

function asyncOperation(index) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log(`Operation for index ${index}`);
            resolve();
        }, 1000);
    });
}

async function runLoops() {
    for (let i = 0; i < 3; i++) {
        await asyncOperation(i);
    }
}

runLoops();   
// Logs each index after 1 second interval

Here, await pauses the loop until each promise resolves.

9. How can you use a for loop to iterate over an array in reverse?

To iterate over an array in reverse order with a for loop, simply start from the last index and decrement:

const arr = ['a', 'b', 'c', 'd'];

for (let i = arr.length - 1; i >= 0; i--) {
    console.log(arr[i]);
}
// d, c, b, a

10. Are there performance differences between for, while, and do...while loops?

All three loop types (for, while, do...while) have similar performance characteristics, mainly differing by syntax. In practice, browsers optimize these loops efficiently, so the choice usually hinges more on readability and logic rather than performance.

To choose wisely, focus on code clarity and the logic that best fits your needs. For example, prefer a for loop when iterating over arrays with known lengths, and while or do...while loops when the iteration count is uncertain:

// Performance test comparing for and while loops
let sum1 = 0, sum2 = 0, n = 10e6;

console.time('for');
for (let i = 0; i < n; i++) {
    sum1 += i;
}
console.timeEnd('for');

console.time('while');
let j = 0;
while (j < n) {
    sum2 += j;
    j++;
}
console.timeEnd('while');

Typically, results won't show significant differences, especially for high iterations, since modern JavaScript engines optimize both constructs equally well.


You May Like This Related .NET Topic

Login to post a comment.