JavaScript While Loop

Learn JavaScript while loop with detailed explanations, syntax, examples, outputs, and real-world practical usage.

JavaScript While Loop

A while loop is used to repeatedly execute a block of code as long as a condition remains true. It is mainly used when the number of iterations is not fixed in advance.

While loops help automate repetitive tasks and make programs more efficient.

Why While Loop is Important?

  • Repeats code automatically
  • Reduces duplicate code
  • Handles dynamic conditions
  • Improves program efficiency
  • Useful when iterations are unknown

Syntax of While Loop

while(condition){

    // code block

}

Explanation of Syntax

  • The condition is checked before every iteration.
  • If the condition is true, the loop executes.
  • If the condition becomes false, the loop stops.

Basic While Loop Example

The following example prints numbers from 1 to 5.

let i = 1;

while(i <= 5){

    console.log(i);

    i++;

}

Output

1

2

3

4

5

Detailed Explanation

  • i = 1 initializes the variable.
  • The condition checks whether i is less than or equal to 5.
  • i++ increases the value after every iteration.
  • The loop stops when i becomes 6.

Reverse While Loop

A while loop can also run in reverse order.

let i = 5;

while(i >= 1){

    console.log(i);

    i--;

}

Output

5

4

3

2

1

Explanation

  • The loop starts from 5.
  • i-- decreases the value after every iteration.
  • The loop stops when i becomes 0.

Printing Even Numbers

While loops can generate patterns and calculations.

let i = 2;

while(i <= 10){

    console.log(i);

    i += 2;

}

Output

2

4

6

8

10

Explanation

  • The loop starts from 2.
  • i += 2 increases the value by 2.
  • Only even numbers are displayed.

Calculating Sum Using While Loop

Loops are commonly used for repeated calculations.

let i = 1;

let sum = 0;

while(i <= 5){

    sum = sum + i;

    i++;

}

console.log(sum);

Output

15

Detailed Explanation

  • sum initially stores 0.
  • The loop adds numbers from 1 to 5.
  • The final result becomes 15.

Infinite While Loop

If the condition never becomes false, the loop runs forever.

let i = 1;

while(i > 0){

    console.log(i);

    i++;

}

Explanation

  • The condition always remains true.
  • The loop never stops.
  • Infinite loops should be avoided.

Using break Statement

The break statement immediately stops the loop.

let i = 1;

while(i <= 10){

    if(i == 5){

        break;

    }

    console.log(i);

    i++;

}

Output

1

2

3

4

Explanation

  • The loop stops when i becomes 5.
  • break terminates loop execution immediately.

Using continue Statement

The continue statement skips the current iteration.

let i = 0;

while(i < 5){

    i++;

    if(i == 3){

        continue;

    }

    console.log(i);

}

Output

1

2

4

5

Explanation

  • The loop skips number 3.
  • continue jumps directly to the next iteration.

Difference Between while and do while

while checks the condition before execution, while do while executes at least once.

let i = 1;

do{

    console.log(i);

    i++;

}while(i <= 3);

Output

1

2

3

Nested While Loop

A while loop inside another while loop is called nested while loop.

let i = 1;

while(i <= 2){

    let j = 1;

    while(j <= 3){

        console.log(i, j);

        j++;

    }

    i++;

}

Output

1 1

1 2

1 3

2 1

2 2

2 3

Explanation

  • The outer loop controls rows.
  • The inner loop runs completely for each outer iteration.
  • Nested loops are useful for tables and patterns.

Complete Real Life Example

The following example shows a simple task list generator using JavaScript while loop.

<!DOCTYPE html>

<html>

<head>

    <title>JavaScript While Loop Example</title>

</head>

<body>

<h2>Daily Task List</h2>

<button onclick="showTasks()">

Show Tasks

</button>

<ul id="output"></ul>

<script>

function showTasks(){

    let tasks = [

        "Wake Up",

        "Exercise",

        "Study JavaScript",

        "Complete Homework",

        "Sleep"

    ];

    let i = 0;

    let result = "";

    while(i < tasks.length){

        result += "<li>" +

        tasks[i] +

        "</li>";

        i++;

    }

    document.getElementById("output").innerHTML =

    result;

}

</script>

</body>

</html>

Output

Daily Task List

• Wake Up
• Exercise
• Study JavaScript
• Complete Homework
• Sleep

Detailed Explanation of Example

  • The array stores task names.
  • The loop starts from index 0.
  • Each task is converted into a list item.
  • i++ moves to the next array item.
  • innerHTML displays generated tasks on the webpage.
  • The loop stops after all tasks are displayed.

Common Mistakes

  • Forgetting to update loop variables.
  • Writing incorrect conditions.
  • Creating infinite loops accidentally.
  • Using wrong array indexes.

Best Practices

  • Always update loop variables properly.
  • Keep conditions simple and readable.
  • Avoid unnecessary nested loops.
  • Prevent infinite loops.
  • Use meaningful variable names.

Important Notes

  • while loops repeat code while conditions remain true.
  • Conditions are checked before execution.
  • break stops loop execution immediately.
  • continue skips current iteration.
  • while loops are useful for dynamic repetition.

Summary

  • while loops execute code repeatedly.
  • Loops continue while conditions are true.
  • Loop variables control execution.
  • break stops loops immediately.
  • continue skips iterations.
  • Nested loops contain loops inside loops.
  • Infinite loops should be avoided.
  • while loops are widely used in programming.