Lesson 31

While Loops

Introduction to while loops

20 min
+25 XP
Step 1 of 5

What is a While Loop?

A while loop repeats code as long as a condition is true. It's like saying "while it's raining, stay inside."

While Loop Structure:

A while loop checks a condition before each repetition. If the condition is true, the code runs again. If false, the loop stops.

let count = 0

while (count < 5) {
  console.log("Count is: " + count)
  count++
}

Important!

Always make sure your condition will eventually become false, or you'll create an infinite loop that never stops!

Key Parts of a While Loop:

  • 1.Condition: Tested before each loop iteration
  • 2.Code Block: The code that repeats
  • 3.Update: Changes that make the condition false eventually