Loops for Repeated Actions

Course: JavaScript Beginner

Lesson 9: Loops for Repeated Actions

Level

Beginner

Estimated Reading Time

10–15 minutes

Goal

By the end of this lesson, the learner will be able to:

  • Use for, while, and for...of loops to repeat actions
  • Choose the right loop type based on whether you are iterating a count, a condition, or a collection
  • Avoid common infinite loop mistakes and use break to exit a loop early

Frontend Development Context

Loops are how JavaScript handles repetition — and repetition is everywhere in frontend work. Rendering a list of products from an array, adding event listeners to multiple buttons, generating a set of HTML cards, checking each item in a cart — all of these require repeating the same action across a collection or a defined number of times.

The most common loop pattern in modern frontend JavaScript is iterating over arrays. When you receive data from an API — a list of users, a collection of blog posts, a set of search results — you will loop over it to build the UI. Knowing which loop to reach for, and how to write it safely, is a core skill.

Explanation

The for loop is the most explicit loop — you define a start value, a condition to keep looping, and an update step, all in one line. It looks like: for (let i = 0; i < 5; i++). The variable i is commonly used as a loop counter (short for "index"). The loop runs as long as the condition is true, and updates i after each iteration.

The while loop repeats a block as long as its condition is truthy. It is useful when you do not know in advance how many times you need to loop — for example, reading items until a flag changes. The condition is checked before each iteration, so if it starts false, the loop body never runs.

The for...of loop iterates over the values in any iterable — most commonly arrays. It is cleaner than a traditional for loop when you just need each item in a collection and do not need the index. for (const item of items) gives you each item one at a time.

The break keyword immediately exits a loop. The continue keyword skips the rest of the current iteration and moves to the next one. Both are useful for early exits and filtering.

One important rule: make sure your loop will eventually stop. Every loop must have a condition that eventually becomes false. Forgetting to update your counter in a while loop creates an infinite loop that freezes the browser tab.

Code Example

This example loops over an array of products and renders them as list items in the DOM:

const products = [
  { name: "Keyboard", price: 79 },
  { name: "Mouse", price: 35 },
  { name: "Monitor", price: 299 },
  { name: "Webcam", price: 89 },
];

const list = document.querySelector("#product-list");

for (const product of products) {
  const item = document.createElement("li");
  item.textContent = `${product.name} — $${product.price}`;
  list.appendChild(item);
}

// for loop to find the first product under $100
let affordable = null;
for (let i = 0; i < products.length; i++) {
  if (products[i].price < 100) {
    affordable = products[i];
    break; // stop as soon as we find one
  }
}
console.log("First affordable:", affordable?.name); // "Keyboard"

Code Explanation

The for...of loop iterates over the products array. On each iteration, product is one object from the array. The loop creates a <li> element, sets its text content using a template literal, and appends it to the #product-list element in the DOM. After 4 iterations, the list is fully populated.

The second loop uses a traditional for loop with an index i. This is useful here because we need access to products[i] by position. The break statement exits the loop as soon as the first product under $100 is found — there is no need to keep checking the rest.

affordable?.name uses optional chaining (?.) as a safety measure — if affordable is still null (no product was under $100), this returns undefined instead of throwing an error.

Choosing between for...of and a traditional for loop often depends on whether you need the index. For simply processing each item, for...of is cleaner. When you need the position, the count, or early exit by index, a traditional for loop gives more control.

Pattern Highlights

Positive Pattern: Use for...of when iterating an array and you only need the values — it is more readable than a traditional for loop and avoids index-related bugs.

⚠️ Neutral Note: for...of does not give you the index by default. If you need both the index and the value, use entries(): for (const [i, item] of items.entries()).

Negative Pattern: Forgetting to increment the counter in a while loop creates an infinite loop that crashes the browser tab. Always ensure the loop condition will eventually become false.

Common Mistakes

Mistake 1: Off-by-one error in a for loop

Using <= instead of < when comparing against .length causes the loop to try to access an index that does not exist.

const colors = ["red", "green", "blue"];

for (let i = 0; i <= colors.length; i++) {
  console.log(colors[i]);
  // When i = 3: colors[3] is undefined — one iteration too many
}

// Correct:
for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}

Array indices go from 0 to length - 1. Always use < (not <=) when looping with i < array.length.

Mistake 2: Mutating an array while iterating over it with for...of

Modifying the array you are iterating over with for...of can cause items to be skipped or processed multiple times.

const items = [1, 2, 3, 4, 5];
for (const item of items) {
  if (item === 3) items.push(6); // modifying the array mid-loop is risky
}
// The loop now sees item 6, which may not be intended behavior

If you need to filter or transform, create a new array rather than modifying the one you are iterating.

Mistake 3: Creating an infinite while loop

Forgetting to update the condition inside a while loop makes it run forever.

let count = 0;
while (count < 5) {
  console.log(count);
  // Missing: count++ — this loop never ends and freezes the browser
}

Always make sure the variable driving the while condition changes inside the loop body so the condition eventually becomes false.

Quick Recap

  • for loops are explicit: define start, condition, and update all in one line — good when you need the index
  • while loops repeat as long as a condition is truthy — good when you do not know the count in advance
  • for...of loops iterate over array values cleanly — the preferred choice for processing collections
  • Use break to exit a loop early and always ensure your loop condition will eventually become false

Ready to test your understanding? Take the quiz to reinforce what you learned.

© 2026 Ant Skillsv.26.07.07-23:01