⬅ Previous Topic
JavaScript For LoopNext Topic ⮕
JavaScript do while Loop Explained with Examples⬅ Previous Topic
JavaScript For LoopNext Topic ⮕
JavaScript do while Loop Explained with ExamplesThe while loop in JavaScript is a control structure that lets you repeat a block of code as long as a condition remains true. It's one of the fundamental building blocks for creating dynamic behavior and automating repetitive tasks.
Think of it like a repeating question: "Should I continue?" If the answer is yes (i.e., the condition is true), the loop runs again. If not, it stops right there.
while (condition) {
// code block to execute
}
The condition
is evaluated before the loop body runs. If it's true, the body executes. If false, the loop exits immediately.
let i = 0;
while (i < 5) {
console.log("Number is: " + i);
i++;
}
Number is: 0
Number is: 1
Number is: 2
Number is: 3
Number is: 4
In this example, i
starts at 0. The loop continues while i < 5
. With each pass, we print the number and increase i
by 1. Once i
reaches 5, the loop stops.
while (true) {
console.log("This will run forever!");
}
Be careful! If the condition never becomes false, the loop will never end — this is called an infinite loop. It can freeze your browser or crash your program.
let password;
while (password !== "secret123") {
password = prompt("Enter the password:");
}
alert("Access granted!");
This loop keeps prompting the user until they type secret123
. Once the correct password is entered, the loop exits, and access is granted.
let fruits = ["apple", "banana", "cherry"];
let index = 0;
while (index < fruits.length) {
console.log(fruits[index]);
index++;
}
apple
banana
cherry
Although for
loops are more common for arrays, while
loops offer greater flexibility when you're not sure how many iterations you need in advance.
let row = 1;
while (row <= 3) {
let col = 1;
while (col <= 3) {
console.log(`Row ${row}, Column ${col}`);
col++;
}
row++;
}
Row 1, Column 1
Row 1, Column 2
Row 1, Column 3
Row 2, Column 1
Row 2, Column 2
Row 2, Column 3
Row 3, Column 1
Row 3, Column 2
Row 3, Column 3
This example demonstrates a grid-like iteration using nested while
loops — often used in matrix operations, games, or simulations.
break
to Exit Early
let x = 1;
while (x <= 10) {
if (x === 5) break;
console.log(x);
x++;
}
1
2
3
4
The break
statement forces the loop to stop completely when x === 5
.
continue
to Skip Iterations
let y = 0;
while (y < 5) {
y++;
if (y === 3) continue;
console.log(y);
}
1
2
4
5
When y === 3
, the continue
skips that iteration — meaning 3
doesn’t get printed.
Choose a while loop when:
let attempts = 0;
let serverReady = false;
while (!serverReady && attempts < 5) {
console.log("Checking server...");
serverReady = Math.random() > 0.7; // Simulate check
attempts++;
}
console.log(serverReady ? "Server is up!" : "Server not ready after 5 attempts.");
This example simulates polling a server status, retrying up to 5 times using a while loop. It’s realistic, practical, and a great example of conditional repetition.
The JavaScript while loop is a powerful tool when your logic depends on conditions rather than known counts. Whether you're validating input, polling an API, or navigating data structures — mastering this loop puts you in control of your code's flow.
Start small. Think logically. Practice deeply. And you'll find that while loops are a gateway to writing more responsive, intelligent programs.
⬅ Previous Topic
JavaScript For LoopNext Topic ⮕
JavaScript do while Loop Explained with 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.