Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

while — a loop that tests before running

The while statement repeats its body while its condition converts to true. It checks the condition before every iteration, so the body might never run.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

while (condition) {
  statements
}

while is a JavaScript keyword and cannot be a variable name. The statement while (condition) { statements } checks condition before every iteration. Its result undergoes ToBoolean conversion: a truthy value runs the body, and a falsy value ends the loop. The condition therefore does not have to produce true or false directly.

The body is a single statement; a block { ... } groups multiple statements. Use braces to make its boundaries clear. Unlike do...while, a while loop can run its body zero times. A semicolon immediately after while (condition) creates an empty body—the following block is then outside the loop.

A break statement exits the loop, while continue skips the rest of the current iteration and returns to the condition check. Ensure that the loop can terminate; in particular, continue can skip a counter update and cause endless repetition.

In the example, count takes the values 1, 2, and 3 inside the body, adding them to total. After count increases to 4, the condition becomes false and the program prints 6.

Examples

let count = 1;
let total = 0;

while (count <= 3) {
  total += count;
  count += 1;
}

console.log(total);

Result

6

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources