Lesson 5: Looping Through Arrays

Learning Objectives

By the end of this lesson, learners will:

  • Understand what arrays are and why we loop through them
  • Learn how to access array items using a loop
  • Use for, while, and for...of loops with arrays
  • Practice writing loops to process and display array contents
  • Learn real-world applications such as filtering, searching, or displaying lists

Why Loop Through Arrays?

An array is a list-like data structure used to store multiple values in one variable.

Example:

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

If you want to:

  • Display all items
  • Filter or search for something
  • Apply an action to each element

…you’ll need to loop through the array.


Using a for Loop with Arrays

Syntax:

for (let i = 0; i < array.length; i++) {
  // use array[i]
}

Example:

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

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

Output:

apple  
banana  
cherry

i starts at 0 (first index)
fruits[i] gets each item
fruits.length is the total number of items


Using a while Loop with Arrays

You can also loop through arrays with a while loop.

Example:

let colors = ["red", "green", "blue"];
let i = 0;

while (i < colors.length) {
  console.log(colors[i]);
  i++;
}

Same output:

red  
green  
blue

Using the for...of Loop (Newer & Cleaner)

for...of is a modern and beginner-friendly way to loop through array values directly — no index needed.

Syntax:

for (let item of array) {
  // use item directly
}

Example:

let animals = ["cat", "dog", "elephant"];

for (let animal of animals) {
  console.log(animal);
}

Output:

cat  
dog  
elephant

✅ Simpler to read
✅ No need to manage index manually
✅ Great for most use cases


Real-World Use Case: Displaying Product Names

let products = ["Laptop", "Phone", "Tablet"];

for (let product of products) {
  console.log("Product: " + product);
}

Output:

Product: Laptop  
Product: Phone  
Product: Tablet

Accessing Index (if needed with for...of)

The for...of loop doesn’t give you the index directly, but you can combine with .entries():

let books = ["Book A", "Book B"];

for (let [index, book] of books.entries()) {
  console.log(index + ": " + book);
}

Output:

0: Book A  
1: Book B

Common Pitfalls

Using <= instead of <:

// BAD: includes undefined!
for (let i = 0; i <= fruits.length; i++) {
  console.log(fruits[i]); // last item is undefined!
}

✅ Always use < fruits.length to stay within bounds.

Confusing index and value:

for (let i = 0; i < fruits.length; i++) {
  console.log(i);        // prints 0, 1, 2 (the index)
  console.log(fruits[i]); // prints the fruit (correct!)
}