Back to course

The 'while' Loop Structure

JavaScript: The Complete '0 to Hero' Beginner Course

38. The while Loop

The while loop runs as long as its specified condition remains true. It is best used when you don't know exactly how many times the loop needs to run (e.g., waiting for user input, or processing database records).

Syntax

javascript initialization; while (condition) { // Code to execute iteration/update; // MUST be included to prevent infinite loops! }

Example

We want to double a value until it exceeds 100.

javascript let total = 5; let steps = 0;

while (total <= 100) { total *= 2; // Double the total steps++; console.log(Current total: ${total}); }

console.log(It took ${steps} steps to exceed 100.);

Infinite Loops

If the condition within the while loop never becomes false, the loop will run forever, freezing your browser or Node environment. Always ensure the loop body modifies a variable that will eventually make the condition false.