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:
- We start with
count = 1
. - The loop checks
count <= 5
. If true, it prints the count and increments it by 1. - Once
count
becomes 6, the condition becomes false and the loop stops.
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:
- We initialize
i
to 1 andsum
to 0. - In each iteration,
i
is added tosum
and incremented. - The loop stops after 10 iterations.
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:
- We simulate guessing a number until it matches the
secret
value. - The loop stops once
guess === secret
.
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:
while(true)
runs endlessly unless we break it manually.break
stops the loop whennum === 3
.
Key Takeaways:
- Always ensure the loop condition eventually becomes false.
- Use
break
cautiously to exit infinite loops safely. while
loops are perfect when you don’t know how many times you'll iterate in advance.
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++;
}