Home » JavaScript while Loop: A Complete Tutorial with Examples

JavaScript while Loop: A Complete Tutorial with Examples

The while loop in JavaScript repeatedly executes a block of code as long as a specified condition evaluates to true.

It is useful when you don't know beforehand how many times you need to repeat a code block.

Syntax of the while Loop

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

condition: The loop continues as long as this expression evaluates to true.
The loop's body is enclosed in curly braces {} and will execute each time the condition is true.

Example 1: Basic while Loop

Let's start with a simple example that prints numbers from 1 to 5 using a while loop.

let number = 1;

while (number <= 5) {
  console.log(number);
  number++; // Increment the number
}

Output:

1
2
3
4
5

Explanation

The loop starts with number set to 1.
It checks if number is less than or equal to 5. If true, it executes the code inside the loop.
console.log(number) prints the current value of number.
number++ increments number by 1.
The loop repeats until number is greater than 5.

Example 2: Using the while Loop for Input Validation

The while loop is often used to validate user input. Here's an example where the loop prompts the user until a valid number is entered.

let userInput = prompt('Enter a number greater than 10:');

while (userInput <= 10) {
  userInput = prompt('Invalid input. Please enter a number greater than 10:');
}

console.log(`You entered: ${userInput}`);

Explanation

The loop continues prompting the user until a number greater than 10 is provided.
prompt() returns the user input as a string, so it’s implicitly converted to a number when compared (<=).
Once a valid number is entered, the loop exits, and the valid input is logged to the console.

Note: This code snippet uses prompt() for input, which is a common way to get input in the browser.

Example 3: Infinite while Loop

An infinite while loop continues forever because the condition always remains true. Here’s an example of an infinite loop (though it's generally a situation to avoid):

while (true) {
  console.log('This will run forever unless manually stopped.');
}

Explanation

The condition true is always true, so the loop will never end on its own.
Important: Infinite loops can crash your program or browser, so they should be used with care and a clear plan to exit.

Example 4: while Loop with break

To exit a while loop prematurely, you can use the break statement.

let count = 1;

while (true) {
  console.log(count);
  count++;
  
  if (count > 5) {
    break; // Exit the loop when count is greater than 5
  }
}

Output:

1
2
3
4
5

Explanation

This is an infinite loop (while (true)), but it contains a break statement.
The loop stops when count exceeds 5.

Example 5: Skipping an Iteration with continue

The continue statement skips the current iteration of the loop and moves to the next one.

let num = 0;

while (num < 10) {
  num++;
  
  if (num % 2 === 0) {
    continue; // Skip the rest of the code inside the loop if num is even
  }
  
  console.log(num); // This will print only odd numbers
}

Output:

1
3
5
7
9

Explanation

The continue statement is used to skip printing the even numbers.
When num % 2 === 0 (i.e., num is even), continue skips the rest of the loop's code and goes to the next iteration.

Example 6: Nested while Loops

You can use nested while loops for more complex scenarios, such as printing a simple multiplication table.

let i = 1;

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

Output:

1 * 1 = 1
1 * 2 = 2
...
5 * 4 = 20
5 * 5 = 25

Explanation

The outer while loop iterates over i from 1 to 5.
The inner while loop iterates over j from 1 to 5 for each i.
It prints the product of i and j in a multiplication table format.

Example 7: Using while Loop with Arrays

The while loop can be used to iterate over an array.

let fruits = ['apple', 'banana', 'cherry'];
let index = 0;

while (index < fruits.length) {
  console.log(fruits[index]);
  index++;
}

Output:

apple
banana
cherry

Explanation

The loop continues as long as index is less than the length of the fruits array.
It accesses each element in the array and prints it to the console.

Conclusion

The while loop is a powerful tool in JavaScript for running a block of code as long as a specified condition remains true. It is particularly useful when you don't know beforehand how many times you need to repeat the loop.

Here are some key points to remember:

Ensure that the condition eventually becomes false to avoid infinite loops.
Use break to exit a loop prematurely when necessary.
Use continue to skip the current iteration and move to the next one.

With this tutorial, you now have a solid understanding of the while loop and its various use cases in JavaScript. Happy coding!

You may also like