Lesson 4: Looping Through Arrays

Lesson Goal:

Learn how to iterate through arrays using different types of loops to access and manipulate each item. This is essential for working with lists of data in real applications.


Why Loop Through Arrays?

When you have a list of items (e.g., usernames, scores, tasks), you often need to:

  • Display all items
  • Modify each item
  • Perform calculations
  • Filter or search for values

Rather than repeating the same code manually, you can use loops to automate this process.


Looping Techniques

for Loop

The classic, most flexible loop:

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

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
  • i is the index
  • fruits[i] accesses each value
  • fruits.length keeps the loop within bounds

for...of Loop

A simpler way to loop through the values in an array:

for (let fruit of fruits) {
  console.log(fruit);
}
  • No need to use index
  • Great for readability

forEach() Method

An array method that takes a callback function and runs it once for each element:

fruits.forEach(function(fruit) {
  console.log(fruit);
});

Or with arrow function:

fruits.forEach(fruit => console.log(fruit));

Try It Yourself

let users = ["Anna", "Ben", "Charlie"];

// Using for loop
for (let i = 0; i < users.length; i++) {
  console.log(i + ": " + users[i]);
}

// Using for...of loop
for (let user of users) {
  console.log("Hello, " + user + "!");
}

Real-World Example: Displaying a List

let shoppingList = ["milk", "bread", "eggs"];

shoppingList.forEach(item => {
  console.log("You need to buy: " + item);
});

Common Pitfalls

  • Off-by-one error: Looping to i <= array.length will go out of bounds
  • Modifying array inside the loop can lead to unexpected behavior
  • Don’t forget that forEach() does not support break or continue