JavaScript While Loop: Entry-Controlled Iteration & State Management

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.

Anatomy of a While Loop

Every properly constructed while loop requires three fundamental components:

  1. Initialization: Declaring and seeding a counter or state variable before the loop.
  2. Test Condition: A boolean expression evaluated at the top of each iteration.
  3. State Update / Increment: Modifying the variable inside the body so the condition eventually terminates.
// 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

Dry-Run Execution Trace Table

Iteration # counter (at check) Condition (counter <= 5) runningTotal After Step counter++ (New Value)
11true0 + 1 = 12
22true1 + 2 = 33
33true3 + 3 = 64
44true6 + 4 = 105
55true10 + 5 = 156
66false (Loop Ends!)15 (Unchanged)6

University Exam Corner (BCA Examination Notes)

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

Next Step

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 →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!