JavaScript

Loops: for, while

Loops let you repeat code without writing it out multiple times. A for loop has three parts, separated by semicolons: for (let i = 0; i < 5; i++) { ... }. First, let i = 0; runs once, before the loop starts. Second, i < 5 is checked before every iteration the loop continues only while it's true. Third, i++ runs after every iteration (it increases i by 1, shorthand for i = i + 1). A while loop is simpler in shape: while (condition) { ... } keeps running as long as the condition stays true. You're responsible for changing something inside the loop that eventually makes the condition false forgetting to do that creates an infinite loop, which freezes the page. for...of is a newer, cleaner way to loop directly over the values in an array: for (const item of ["a", "b", "c"]) { console.log(item); } you'll use this constantly once you reach the arrays topic next.

Why this matters

  • ·Loops let you repeat an action many times without duplicating code.
  • ·A for loop's three parts keep the counter, condition, and increment all visible in one line.
  • ·for...of makes looping over a list of values short and readable.

Common mistakes

  • ·A while loop whose condition never becomes false creates an infinite loop, which can freeze the browser tab.
  • ·Off-by-one mistakes (using <= instead of <, or starting at 1 instead of 0) are extremely common in loops.
  • ·Modifying a loop's counter variable unexpectedly inside the loop body can cause confusing, hard-to-predict behavior.
Your codeHTML
Live preview

Frequently asked questions

A starting point (run once), a condition (checked before every loop), and an update step (run after every loop).

Practice questions

Question 1

Write a for loop that displays the numbers 1 through 10.

Your codeHTML
Live preview

Question 2

Write a while loop that counts down from 5 to 1.

Your codeHTML
Live preview

Quick check

Just for this topic answer honestly, then check yourself.

1 / 3

How many parts does a for loop's header have?