← Learning Hub
Beginner

Loops

Loops repeat code. A for loop is ideal when you know how many times to repeat. It has three parts: a start, a condition to keep going, and a step.

Loops save you from writing the same code again and again. Showing 50 products on a page, adding up every item's price, checking every field in a form - a loop does it for each item, whether there are 3 or 3,000.

In for (let i = 1; i <= 10; i++): let i = 1 runs once at the start, i <= 10 is checked before each round, and i++ (add 1) runs after each round. When the condition is false, the loop ends.

Example
<!DOCTYPE html>
<html>
  <body>
    <h3>Table of 7</h3>
    <ul id="list"></ul>
    <script>
      const list = document.getElementById("list");
      for (let i = 1; i <= 10; i++) {
        const li = document.createElement("li");
        li.textContent = "7 x " + i + " = " + (7 * i);
        list.appendChild(li);
      }
    </script>
  </body>
</html>
▶ Try it yourself

A while loop repeats as long as its condition stays true. To go through every item in an array, for...of is the simplest.

Example
const fruits = ["mango", "banana", "guava"];
for (const fruit of fruits) {
  console.log(fruit);
}
Make sure a loop can end. If the condition never becomes false, the loop runs forever and the page freezes.
Key points
  • for when you know how many times; while while a condition holds.
  • for...of goes through every item in an array.
  • Make sure every loop can end.

📝 Test yourself

1. How many times does for (let i = 1; i <= 10; i++) run?
2. Which loop is simplest for every item in an array?
3. Fill in the operator that adds 1 to i:
i;