Mastering the
while loop in JavaScript



Understanding the while Loop

The while loop in JavaScript allows code to be executed repeatedly based on a given condition. As long as the condition evaluates to true, the block inside the loop runs. It’s useful when you don't initially know how many times the loop should run.

Example 1: Printing Numbers from 1 to 5

This is a classic beginner example. Let’s print numbers 1 through 5 using a while loop.


let count = 1;

while (count <= 5) {
  console.log("Count is:", count);
  count++;
}
    

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
    

Code Description:

Question:

What happens if we forget to increment count?

Answer: The loop becomes infinite, because the condition never becomes false!

Example 2: Sum of First 10 Natural Numbers

Let’s use a while loop to calculate the sum of numbers from 1 to 10.


let i = 1;
let sum = 0;

while (i <= 10) {
  sum += i;
  i++;
}

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

Output:

Sum of numbers from 1 to 10 is: 55
    

Code Description:

Example 3: Loop Until User Input is Correct (Simulated)

Let’s simulate a scenario where we repeat an operation until a specific value is reached.


let secret = 7;
let guess = 1;

while (guess !== secret) {
  console.log("Trying guess:", guess);
  guess++;
}

console.log("Correct guess found:", guess);
    

Output:

Trying guess: 1
Trying guess: 2
Trying guess: 3
Trying guess: 4
Trying guess: 5
Trying guess: 6
Correct guess found: 7
    

Code Description:

Example 4: Infinite Loop with Manual Break

Sometimes we use an infinite loop and manually break it using break. Let’s see how that works.


let num = 1;

while (true) {
  console.log("Current number:", num);
  if (num === 3) {
    console.log("Breaking the loop");
    break;
  }
  num++;
}
    

Output:

Current number: 1
Current number: 2
Current number: 3
Breaking the loop
    

Code Description:

Key Takeaways:

Try It Yourself

Write a while loop that prints only even numbers from 1 to 20. Think: How can you skip odd numbers?

Answer:


let num = 1;

while (num <= 20) {
  if (num % 2 === 0) {
    console.log(num);
  }
  num++;
}
    


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M