JavaScript Foundations·The beginner gaps

Loops and iteration

Repeat work with for, for...of and while, and know when an array method is better.

Beginner 12 min read Lesson 5 of 480 Challenge included
What you will be able to do
  • Write for, for...of and while loops
  • Use break and continue to control a loop
  • Decide when an array method is clearer than a loop

In plain English

A loop is a block of code that runs repeatedly while a condition is true. A for loop runs a fixed number of times with a counter, and a while loop keeps running until a condition turns false. A for...of loop visits each item of an array one by one, which is the cleanest way to read every value. The break keyword exits a loop early and continue skips to the next round; when you only need to read or change an array, methods like map, filter and forEach do the looping for you and are often easier to read.

Step by step

  1. 1Use for...of to add up the numbers in an array.
  2. 2Write a while loop that counts down to zero.
  3. 3Add a break so the loop stops early when a condition is met.
  4. 4Replace a simple loop with map, filter or forEach and compare readability.
loops.jsJavaScript
const scores = [12, 45, 33, 50, 41];

let total = 0;
for (const score of scores) {
  total = total + score;
}
console.log("Total:", total);

let countdown = 3;
while (countdown > 0) {
  console.log(countdown);
  countdown = countdown - 1;
}

const passed = scores.filter((score) => score >= 40);
console.log("Passed:", passed);

Common mistakes

  • Creating an infinite loop by forgetting to change the counter or condition inside a while loop.
  • Using a classic for loop with an index when for...of would be clearer.
  • Confusing break (stop the whole loop) with continue (skip one round).
  • Modifying an array while you loop over it, which causes confusing results.
Your turn

First passing score

Easy

Write a function firstPassing(scores) that returns the first score that is 40 or more. Return null if none pass.

JAVASCRIPT · starter
function firstPassing(scores) {
}
Check your understanding before moving on.
Knowledge checkQuestion 1

Which statement skips the current round and moves to the next one?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: JSON and data
Lesson 5 of 480 · 0% of course