JavaScript for Loop VS while Loop

This article is a complementary resource to the Learn JavaScript Basics course.

 

JavaScript for Loop VS while Loop

Loops are a fundamental concept in programming, allowing you to repeat blocks of code. In JavaScript, both for and while loops are used for this purpose, but each has its strengths and ideal use cases.

However, the key question is: When should you use which loop?

Understanding when to use each loop type will help you write more efficient, readable, and maintainable code.

Let's compare the for and while loop with examples.


Example 1: Find the Sum of Numbers from 1 to 5

Both for and while loops can calculate the sum of numbers from 1 to 5, but the for loop is generally more concise when the range is predetermined.

Using for Loop

let total = 0;
for (let i = 1; i <= 5; i++) {
    total += i;
}
console.log(total);    // Output: 15

Using while Loop

let i = 1;
let total = 0;
while (i <= 5) {
    total += i;
    i++;
}
console.log(total);    // Output: 15

Both loops achieve the same result.

However, the for loop is more concise when the number of iterations is known. In this case, we know in advance that the loop needs to run 5 times to calculate the sum of numbers from 1 to 5.

The while loop, on the other hand, requires manual initialization and updating of the loop variable (i).


Example 2: Receive Input Until User Enters 0

In situations where you don't know how many times a task needs to be repeated, a while loop is often more intuitive.

Consider this task of receiving input from user until they enter 0.

Using while Loop

let number = Number(prompt("Enter a number: "));

while (number !== 0) {
    console.log(`The number you entered is ${number}.`);
    number = Number(prompt("Enter a number: "));
}

Using for loop

Recreating the above program using the for loop requires unnecessary workarounds. For example, you'd need to set up an arbitrarily large range and then add a break condition.

for (let i = 0; i < 1000000; i++) {    // Large range to be sure we reach the target sum
    let number = Number(prompt("Enter a number: "));
    if (number === 0) {
        break;
    }
    console.log(`The number you entered is ${number}.`);
}

While this works, it's not ideal.

The while loop is more intuitive and efficient in this case, as it doesn't require guessing the range or dealing with unnecessary iterations.


Takeaway:

  • Use for loops when the number of iterations is known or fixed.
  • Use while loops when the number of iterations is uncertain.