A while loop is an entry-controlled loop in JavaScript. It evaluates a test condition before each iteration; as long as the condition remains truthy, the statements inside the loop body execute repeatedly. If the condition evaluates to false on the very first check, the loop body is bypassed entirely.
Every properly constructed while loop requires three fundamental components:
// Example: Summing numbers from 1 to 5
let counter = 1; // 1. Initialization
let runningTotal = 0;
while (counter <= 5) { // 2. Test Condition
runningTotal += counter;
console.log(`Added ${counter}, Current Total = ${runningTotal}`);
counter++; // 3. State Update (CRITICAL to prevent infinite loops!)
}
console.log("Final Sum:", runningTotal); // 15
| Iteration # | counter (at check) |
Condition (counter <= 5) |
runningTotal After Step |
counter++ (New Value) |
|---|---|---|---|---|
| 1 | 1 | true | 0 + 1 = 1 | 2 |
| 2 | 2 | true | 1 + 2 = 3 | 3 |
| 3 | 3 | true | 3 + 3 = 6 | 4 |
| 4 | 4 | true | 6 + 4 = 10 | 5 |
| 5 | 5 | true | 10 + 5 = 15 | 6 |
| 6 | 6 | false (Loop Ends!) | 15 (Unchanged) | 6 |
Exam Question: "Write a JavaScript program using a while loop to reverse a positive integer (e.g., 12345 to 54321)."
function reverseInteger(num) {
let reversed = 0;
while (num > 0) {
let lastDigit = num % 10; // Extract last digit
reversed = (reversed * 10) + lastDigit; // Shift and append
num = Math.floor(num / 10); // Truncate last digit
}
return reversed;
}
console.log(reverseInteger(12345)); // Output: 54321
console.log(reverseInteger(98701)); // Output: 10789
What if you need a loop to execute at least once, even if the condition is false initially? Proceed to: JavaScript Do While Loop: Exit-Controlled Loops →