⬅ Previous Topic
JavaScript For Loop ExamplesNext Topic ⮕
JavaScript do while Loop Examples⬅ Previous Topic
JavaScript For Loop ExamplesNext Topic ⮕
JavaScript do while Loop Exampleswhile
LoopThe 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.
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++;
}
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
count = 1
.count <= 5
. If true, it prints the count and increments it by 1.count
becomes 6, the condition becomes false and the loop stops.What happens if we forget to increment count
?
Answer: The loop becomes infinite, because the condition never becomes false!
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);
Sum of numbers from 1 to 10 is: 55
i
to 1 and sum
to 0.i
is added to sum
and incremented.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);
Trying guess: 1 Trying guess: 2 Trying guess: 3 Trying guess: 4 Trying guess: 5 Trying guess: 6 Correct guess found: 7
secret
value.guess === secret
.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++;
}
Current number: 1 Current number: 2 Current number: 3 Breaking the loop
while(true)
runs endlessly unless we break it manually.break
stops the loop when num === 3
.break
cautiously to exit infinite loops safely.while
loops are perfect when you don’t know how many times you'll iterate in advance.Write a while loop that prints only even numbers from 1 to 20. Think: How can you skip odd numbers?
let num = 1;
while (num <= 20) {
if (num % 2 === 0) {
console.log(num);
}
num++;
}
⬅ Previous Topic
JavaScript For Loop ExamplesNext Topic ⮕
JavaScript do while Loop ExamplesYou 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.