Learn JavaScript from Scratch

Loops in JavaScript

Lesson 4 of 9 2 min read Updated 10 October 2026

Why loops?

Loops repeat code so you do not have to write it many times.

for loop

<script>
for (let i = 1; i <= 5; i++) {
  document.write("Line " + i + "<br>");
}
</script>

A for loop has three parts: start (let i = 1), condition (i <= 5) and step (i++).

while and do while

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

let x = 0;
do {
  console.log("Runs at least once");
  x++;
} while (x < 1);

for…of (values) and for…in (keys)

const fruits = ["mango", "banana", "apple"];
for (const f of fruits) {
  console.log(f);
}

const student = { name: "Asha", age: 20 };
for (const key in student) {
  console.log(key, student[key]);
}

break and continue

for (let i = 1; i <= 10; i++) {
  if (i === 3) continue;  // skip 3
  if (i === 6) break;     // stop at 6
  console.log(i);
}

Example: multiplication table

<script>
const num = 7;
for (let i = 1; i <= 10; i++) {
  document.write(num + " x " + i + " = " + num * i + "<br>");
}
</script>

Note: A loop whose condition never becomes false runs forever and can freeze the page. Always make sure the loop moves toward its end.

Practice

Print the sum of numbers from 1 to 100, and print the numbers from 1 to 50 that are divisible by both 3 and 5.

Practice tasks

Reading is not enough. Try these without copying code, then compare with the lesson.

  • Print numbers 1 to 20 with a for loop.
  • Sum an array with a for…of loop.
  • Use a while loop to repeat until a condition is met.

Common mistakes

  • Creating an infinite loop by not updating the counter.
  • Off-by-one mistakes in loop limits.

Quick check

When would you use a while loop?

When the number of repeats is not known beforehand.

What does break do?

It exits the loop immediately.