LOGBOOK

HELP

Quiz Entry - updated: 2026.06.20

How do you write a while loop in JavaScript?

A while loop repeats a block of code over and over for as long as its condition stays true.

Loops let you repeat work without copying code. A while loop checks a condition before each pass; while it's true, the block runs again:

let i = 0;
let sum = 1;
while (i < 5) {
    console.log('sum: ' + sum);
    sum = sum + sum;
    i = i + 1;   // move toward the exit condition!
}
// Output: sum: 1, sum: 2, sum: 4, sum: 8, sum: 16

Every well-behaved loop has three moving parts:

  1. Initialise the loop variable (let i = 0)
  2. Check the condition (i < 5)
  3. Update the loop variable each pass (i = i + 1)

The most important gotcha is step 3: if you forget to move the loop variable toward the condition becoming false, the condition stays true forever and you get an infinite loop that freezes the page.

while isn't the only loop. JavaScript also has for (compact syntax for counting loops), do-while (runs the body once before checking, so it always executes at least once), and for...in / for...of for stepping through an object's keys or an array's elements.

From Quiz: WEBT / Introduction to JavaScript | Updated: Jun 20, 2026