TechLead
Lesson 8 of 16

Loops

Repeat actions over lists of data without rewriting code.

Quick Summary

Loops run a block multiple times until a condition is false or a list ends. Use for and while for counters, and for...of to iterate through arrays cleanly. Understanding when to use each loop type makes your code cleaner and less error-prone.

Why Use Loops?

Without loops, processing a list of 100 items would require 100 lines of code. Loops let you process any number of items with just a few lines.

for Loop

Best when you know how many times to iterate:

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

Structure: for (initialization; condition; update)

for...of Loop

Best for arrays and iterables (recommended):

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

for...in Loop

For object properties (use carefully):

const user = { name: "Alice", age: 30 };
for (const key in user) {
  console.log(key + ": " + user[key]);
}

while Loop

Run while condition is true:

let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}

do...while Loop

Always runs at least once:

let num = 10;
do {
  console.log(num); // Runs once even though condition is false
  num++;
} while (num < 5);

Loop Control

break - Exit the loop immediately:

for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i); // 0, 1, 2, 3, 4
}

continue - Skip to next iteration:

for (let i = 0; i < 5; i++) {
  if (i === 2) continue;
  console.log(i); // 0, 1, 3, 4
}

Common Loop Patterns

// Sum all numbers
let total = 0;
for (const num of [1, 2, 3, 4, 5]) {
  total += num;
}

// Find an item
let found = null;
for (const item of items) {
  if (item.id === targetId) {
    found = item;
    break;
  }
}

// Transform each item
const doubled = [];
for (const num of numbers) {
  doubled.push(num * 2);
}

Try It Yourself

Here's a practical example you can try. Copy this code and run it in your browser's console (press F12 to open developer tools) or in the Code Playground.

// for loop - when you know the count
for (let i = 1; i <= 5; i++) {
  console.log("Count: " + i);
}

// for...of - iterate over arrays (preferred)
const colors = ["red", "green", "blue"];
for (const color of colors) {
  console.log("Color: " + color);
}

// while loop - when condition determines end
let attempts = 0;
while (attempts < 3) {
  console.log("Attempt " + (attempts + 1));
  attempts++;
}

// Building a new array with a loop
const numbers = [1, 2, 3, 4, 5];
const squared = [];
for (const num of numbers) {
  squared.push(num * num);
}
console.log(squared); // [1, 4, 9, 16, 25]

// Using break to exit early
for (let i = 0; i < 100; i++) {
  if (i === 5) {
    console.log("Found 5, stopping!");
    break;
  }
}

// Using continue to skip iterations
for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue; // Skip even numbers
  console.log(i); // 1, 3, 5, 7, 9
}

Key Takeaways

  • Repeat actions over lists of data without rewriting code.
  • Practice with real code examples to solidify your understanding
  • This concept builds the foundation for more advanced topics

Related Learning Resources

Continue your programming journey with these related tutorials: