Back to JavaScript
2025-12-267 min read

While Loop with else (JavaScript)

Learn While Loop with else (JavaScript) step by step with clear examples and exercises.

Title: Mastering JavaScript's While Loop with an Else Statement

Why This Matters

The while loop is a fundamental control structure in JavaScript that allows you to repeatedly execute a block of code as long as a specified condition is true. The addition of the else statement can significantly enhance your programming skills by allowing you to handle specific cases or conditions that may occur when the main loop has completed, such as printing messages indicating that the loop has finished or performing cleanup tasks before exiting the loop. This lesson will guide you through the core concept, worked example, common mistakes, practice questions, and frequently asked questions related to using the while loop with an else statement in JavaScript.

Prerequisites

Before diving into the while loop with an else statement, it is essential to have a solid understanding of the following concepts:

  • Variables and data types in JavaScript
  • Basic arithmetic operations in JavaScript
  • Conditional statements (if/else) in JavaScript
  • The basic structure of a for loop in JavaScript
  • Understanding how to break out of loops using the break keyword
  • Familiarity with arrays and array methods, such as push(), pop(), and length

Core Concept

The while loop is used to repeatedly execute a block of code as long as a specified condition is true. The syntax for a while loop with an optional else statement is as follows:

while (condition) {
// code to be executed while the condition is true
}
[else] {
// code to be executed when the condition becomes false
}

The while loop continues to execute its body until the specified condition evaluates to false. If an else statement is present, it will only execute once the loop has completed and the condition has become false.

Example: Counting from 1 to 5 using a while loop with an else statement

let num = 1;

while (num <= 5) {
console.log(num);
num++;
}

console.log("Loop completed.");

// In this example, we initialize a variable `num` to 1 and set up a `while` loop that continues as long as `num` is less than or equal to 5. Inside the loop, we print the value of `num`, increment it by 1, and continue with the next iteration. Once `num` exceeds 5, the loop terminates, and we print "Loop completed."

If we were to omit the else statement and instead print a message inside the while loop upon reaching 6, the loop would not execute the message since it would immediately exit once the condition is no longer true. By using an else statement, we ensure that the message is printed only after the loop has completed its iterations.

Example: Counting backwards from 5 to 1 using a while loop with an else statement

let num = 5;

while (num > 0) {
console.log(num);
num--;
}

console.log("Loop completed.");

// In this example, we initialize a variable `num` to 5 and set up a `while` loop that continues as long as `num` is greater than 0. Inside the loop, we print the value of `num`, decrement it by 1, and continue with the next iteration. Once `num` reaches 0, the loop terminates, and we print "Loop completed."

Common Mistakes

  1. ### Forgetting to initialize the control variable

It is essential to properly initialize the control variable before entering a while loop. If you forget to do so, the loop may not behave as expected or may cause an infinite loop.

let num = 5;

while (num > 0) {
console.log(num);
}

// In this example, we have forgotten to initialize `num` before the loop, which will cause an infinite loop since the condition is always true.
  1. ### Neglecting to update the control variable

If you forget to update the control variable inside the loop, the loop may not terminate when expected, resulting in an infinite loop or unexpected behavior.

let num = 5;

while (num > 0) {
console.log(num);
}

// In this example, we have forgotten to update `num` inside the loop, which will cause an infinite loop since the condition is always true.
  1. ### Using a non-boolean condition

The condition inside the while loop should always be a boolean expression. If you use a non-boolean value, the loop may behave unexpectedly or result in an infinite loop.

let num = 5;

while (num) { // Using a non-boolean condition
console.log(num);
num--;
}

// In this example, we are using the non-boolean value `num` as the condition for the while loop, which will cause an infinite loop since the condition is always true when `num` is greater than 0.
  1. ### Not handling edge cases

When using a while loop with an else statement, it is important to consider edge cases that might cause the loop to behave unexpectedly or result in infinite loops. For example, if you are using a loop to iterate through an array and the array length changes during the loop's execution, this can lead to unintended behavior.

let arr = [1, 2, 3];
let i = 0;

while (i < arr.length) {
console.log(arr[i]);
i++;
}

// If the array is modified during the loop's execution, this could lead to unintended behavior
arr.push(4);

Worked Example

Example: Counting from 1 to 10 using a while loop with an else statement and handling edge cases

let num = 1;
let arr = [];

while (num <= 10) {
arr.push(num); // Add the current number to the array
console.log(num);
num++;
}

console.log("Numbers from 1 to 10: ", arr);

// In this example, we initialize a variable `num` to 1 and set up a `while` loop that continues as long as `num` is less than or equal to 10. Inside the loop, we add the current number to an array called `arr`, print the value of `num`, increment it by 1, and continue with the next iteration. Once `num` exceeds 10, the loop terminates, and we print the numbers from 1 to 10 that were stored in the `arr`.

Example: Counting backwards from 5 to 1 using a while loop with an else statement and handling edge cases

let num = 5;
let arr = [];

while (num > 0) {
arr.push(num); // Add the current number to the array
console.log(num);
num--;
}

console.log("Numbers from 5 to 1: ", arr);

// In this example, we initialize a variable `num` to 5 and set up a `while` loop that continues as long as `num` is greater than 0. Inside the loop, we add the current number to an array called `arr`, print the value of `num`, decrement it by 1, and continue with the next iteration. Once `num` reaches 0, the loop terminates, and we print the numbers from 5 to 1 that were stored in the `arr`.

Practice Questions

  1. Write a while loop that prints the even numbers between 2 and 10 using an else statement to handle the case when the number becomes odd.
let num = 2;

while (num <= 10) {
if (num % 2 !== 0) { // Check if the number is even
console.log("Skipping odd number: " + num);
num++;
continue;
}
console.log(num);
num += 2; // Increment by 2 to get the next even number
}
  1. Implement a while loop with an else statement that calculates the factorial of a given number n. The loop should continue multiplying n by each integer from n-1 down to 1 until it reaches 1, at which point the loop terminates and the factorial is printed.
function factorial(n) {
let result = 1;
let i = n;

while (i > 1) {
console.log(`Calculating factorial for ${i}`);
result *= i;
i--;
}

console.log(`Factorial of ${n} is: ${result}`);
}

factorial(5); // Output: Calculating factorial for 5, Calculating factorial for 4, Calculating factorial for 3, Calculating factorial for 2, Factorial of 5 is: 120

FAQ

### Why use an else statement with a while loop?

Using an else statement with a while loop allows you to handle specific cases or conditions that may occur when the main loop has completed, such as printing messages indicating that the loop has finished or performing cleanup tasks before exiting the loop.

### Can I use multiple else statements in a while loop?

Yes, you can have multiple else if statements within a single while loop. Each else if statement will be executed when the main loop terminates and no other else if or else blocks are found to match the current condition.

### How do I break out of a while loop?

To break out of a while loop, you can use the break keyword inside the loop. When the break statement is encountered, the loop immediately terminates, and control passes to the next statement outside the loop.

let num = 5;

while (num > 0) {
console.log(num);
if (num === 3) { // Break out of the loop when num equals 3
break;
}
num--;
}

### How can I avoid infinite loops with a while loop?

To avoid infinite loops with a while loop, make sure that the condition inside the loop will eventually become false. This can be achieved by properly initializing and updating the control variable, as well as handling edge cases that might cause the loop to continue indefinitely. Additionally, you can use the break keyword to exit the loop when a specific condition is met.

While Loop with else (JavaScript) | JavaScript | XQA Learn