Course contentsShow
← JavaScript
Lesson 337 of 2,72310. LoopsFree lesson

The While Loop

Learn the basic while loop syntax and how it repeatedly executes code as long as a condition is true.

The While Loop

What you'll learn: How to use the while loop to repeat code automatically as long as a condition remains true.

The Core Idea

A while loop is like a repeating if statement. Instead of executing a block of code once when a condition is true, the while loop keeps executing that block over and over—as long as the condition stays true. Once the condition becomes false, the loop stops.

Think of it like this: imagine you're told to "keep stirring the pot while it's boiling." You check if it's boiling, stir, check again, stir... and stop when it's no longer boiling. That's exactly how a while loop works.

Basic Syntax

while (condition) {
  // code to execute repeatedly
}

The loop checks the condition before each iteration. If it's true, the code block runs. If it's false (or becomes false), the loop exits immediately.

Simple Example

let count = 1;

while (count <= 3) {
  count = count + 1;
}
// After loop: count is 4

Here, the loop runs while count is less than or equal to 3. Each time through, count increases by 1. When count reaches 4, the condition becomes false, and the loop stops.

Watch Out for Infinite Loops

If the condition never becomes false, the loop runs forever:

let x = 1;
while (x > 0) {
  x = x + 1; // x keeps growing, always > 0!
}
// This never stops!

Always ensure your loop's condition will eventually become false.

Key Takeaway: The while loop repeatedly executes code as long as its condition evaluates to true, checking the condition before each iteration.