Curriculum / Fundamentals / Lesson 06

Loops in JavaScript

Learn for, while, and do-while loops — and when to use each one.

6 of 30
beginner 📖 6 min read 🎯 4 questions

What Are Loops?

Loops allow you to repeat a block of code multiple times. Instead of writing the same code 10 times, you write it once and let the loop handle the repetition.

💡 Real-world analogy Counting from 1 to 10 is a loop. Each time you say the next number, you're repeating the same action until you reach the end.

The for Loop

The most common loop. Use it when you know how many times you want to repeat something.

for (let i = 0; i < 5; i++) {
  console.log("Count:", i);
}
// Output: 0, 1, 2, 3, 4

The while Loop

Use when you don't know how many times you'll need to repeat — the loop continues while a condition is true.

let count = 0;
while (count < 3) {
  console.log("While count:", count);
  count++;
}

The do-while Loop

Similar to while, but the code runs at least once before checking the condition.

let x = 5;
do {
  console.log("Do-while:", x);
  x++;
} while (x < 3);
// Runs once even though x is not less than 3

Looping Through Arrays

One of the most common uses of loops is to process each item in an array.

let fruits = ["apple", "banana", "orange"];

for (let i = 0; i < fruits.length; i++) {
  console.log("I like", fruits[i]);
}

Breaking and Continuing

for (let i = 0; i < 10; i++) {
  if (i === 5) break;     // stops at 5
  if (i % 2 === 0) continue; // skips even numbers
  console.log(i); // 1, 3
}

Common Mistakes

Quick Quiz

1. How many times does this loop run?
for (let i = 0; i < 3; i++) { }

2. Which loop runs the code at least once?

3. What does break do in a loop?

Summary

Back to curriculum