JavaScript while Loop
Repeating code while a condition remains true
⏳ What is a while Loop?
The while loop repeats code as long as a condition is true. It's perfect when you don't know exactly how many times you need to loop.
// Basic while loop syntax
while (condition) {
// Code to repeat
// Don't forget to update the condition!
}
// Example: Count from 1 to 5
let count = 1;
while (count <= 5) {
console.log("Count: " + count);
count++; // Important: update the condition!
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
while vs for Loop
while Loop
Use when iterations are unknown
let password = "";
while (password !== "secret") {
password = prompt("Enter password:");
}
for Loop
Use when iterations are known
for (let i = 0; i < 10; i++) {
console.log(i);
}
Condition-Based
while loops check condition first
let found = false;
while (!found) {
// Keep searching...
}
Counter-Based
for loops have built-in counter
for (let i = 0; i < arr.length; i++) {
// Process array[i]
}
🔹 Basic while Loop Examples
Let's explore different while loop patterns:
🔸 Simple Counter
// Count from 0 to 4
let i = 0;
while (i < 5) {
console.log("Number: " + i);
i++; // Don't forget this!
}
Output:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
🔸 Sum Until Limit
// Add numbers until sum reaches 50
let sum = 0;
let num = 1;
while (sum < 50) {
sum += num;
console.log(`Added ${num}, sum is now ${sum}`);
num++;
}
Output:
Added 1, sum is now 1
Added 2, sum is now 3
Added 3, sum is now 6
Added 4, sum is now 10
Added 5, sum is now 15
Added 6, sum is now 21
Added 7, sum is now 28
Added 8, sum is now 36
Added 9, sum is now 45
Added 10, sum is now 55
🔸 Process Array Elements
// Process array with while loop
const colors = ["red", "green", "blue", "yellow"];
let index = 0;
while (index < colors.length) {
console.log(`Color ${index + 1}: ${colors[index]}`);
index++;
}
Output:
Color 1: red
Color 2: green
Color 3: blue
Color 4: yellow
🔹 do...while Loop
The do...while loop runs the code at least once, then checks the condition:
// do...while syntax
do {
// Code runs at least once
} while (condition);
// Example: Menu system
let choice;
do {
console.log("Menu:");
console.log("1. Play Game");
console.log("2. Settings");
console.log("3. Exit");
choice = prompt("Enter your choice (1-3):");
if (choice === "1") {
console.log("Starting game...");
} else if (choice === "2") {
console.log("Opening settings...");
}
} while (choice !== "3");
console.log("Goodbye!");
Key Difference:
while:
Checks condition first, might not run at all
do...while:
Runs code first, then checks condition
🔹 Real-World while Loop Examples
Practical applications of while loops:
🔸 Input Validation
// Keep asking until valid input
let age;
while (age < 0 || age > 120 || isNaN(age)) {
age = parseInt(prompt("Enter your age (0-120):"));
if (age < 0 || age > 120 || isNaN(age)) {
console.log("Invalid age! Please try again.");
}
}
console.log("Valid age entered: " + age);
🔸 Search in Array
// Find first occurrence of a value
const numbers = [5, 12, 8, 130, 44];
const target = 8;
let index = 0;
let found = false;
while (index < numbers.length && !found) {
if (numbers[index] === target) {
found = true;
console.log(`Found ${target} at index ${index}`);
} else {
index++;
}
}
if (!found) {
console.log(`${target} not found in array`);
}
🔸 Generate Random Numbers
// Generate random numbers until we get a specific one
let randomNum;
let attempts = 0;
while (randomNum !== 7) {
randomNum = Math.floor(Math.random() * 10) + 1; // 1-10
attempts++;
console.log(`Attempt ${attempts}: Got ${randomNum}`);
}
console.log(`Success! Got 7 after ${attempts} attempts`);
🔹 Common while Loop Pitfalls
⚠️ Avoid Infinite Loops:
// ❌ BAD: This will run forever!
let count = 0;
while (count < 10) {
console.log(count);
// Forgot to increment count!
}
// ✅ GOOD: Always update the condition
let count = 0;
while (count < 10) {
console.log(count);
count++; // This makes the condition eventually false
}
💡 Best Practices:
- Always update the condition: Make sure the loop can end
- Initialize variables: Set starting values before the loop
- Use meaningful conditions: Make the logic clear
- Consider break statements: For complex exit conditions
- Test edge cases: What if the condition is false from the start?