Programming Basics: Your First Steps

Lesson 4 of 5

Loops: Repeating Actions

Loops let you repeat code without copy-pasting it, essential once you need to process more than a handful of items.

JavaScript

for loops

A classic for (init; condition; increment) loop: let i = 1 runs once at the start, i <= 5 is checked before every pass, i++ runs after every pass. Together they count from 1 to 5, printing a line each time.

for...of loops

for (const s of scores) visits every element in an array directly, no counter needed, use it whenever you don't care about the index, just each value.

while loops

JavaScript

A while (condition) { ... } loop keeps running as long as condition stays true, checked before every pass. Unlike for, nothing about a while loop's structure guarantees it'll ever stop, forgetting to update attempts here would loop forever, always make sure something inside the loop moves it toward false.

📝 Loops Quiz

Passing score: 70%
  1. 1.Which loop is the best fit for visiting every element of an array without needing an index?

  2. 2.In for (let i = 1; i <= 5; i++), the i++ part runs ____ every pass through the loop.

  3. 3.A while loop is guaranteed to stop on its own, even if nothing inside it changes the condition.