← Back to Course

🔁 Different Types of Loops

Loops repeat a block of code. They are useful when you need to do the same kind of work multiple times.

For Loop

Example: Count from 1 to 3

for (let index = 1; index <= 3; index++) {
  console.log(index);
}

While Loop

Example: Repeat Until Done

let attempts = 0;

while (attempts < 3) {
  console.log("Trying again...");
  attempts++;
}

For...of and forEach

Example: Loop Through an Array

const topics = ["loops", "functions", "JSON"];

for (const topic of topics) {
  console.log(topic);
}

topics.forEach((topic) => {
  console.log(`Review ${topic}`);
});

🎯 Key Ideas

  • Use for when you need an index or exact count
  • Use while when the stop condition is the main focus
  • Use for...of for readable iteration over arrays
← Back to Code Foundations