HAP studying on his laptop

Station 5: Repeating Actions

Loops and Arrays

Welcome to Station 5! I had built a great function to check if a skill was active. But then I realized I had TEN skills to check — and I was calling the function separately for each one!

I asked Prof. Teeters, "Is there a way to run the same code for every item in a list?"

She smiled and said, "HAP, think of a for loop like a robot arm on an assembly line. It starts at position 0, does its job, moves to the next position, and keeps going until it reaches the end. The three parts tell it: where to start, when to stop, and how to move."

That's when I learned about loops — code that repeats automatically so you don't have to copy and paste!

Let me show you how to process entire lists with just a few lines of code... 🟠

🔬 Try it yourself: Skill Scanner →

What You'll Learn at This Station

HAP's Discovery: I was copying and pasting the same function call ten times — once for each skill. Then I learned that a single for loop could do all that work automatically, and if I added more skills later, the loop would handle them too!

📦 Arrays (Collections)

[ ]

Arrays store multiple values in order. Access items by their position (index), starting from 0.

🔄 For Loops (Repetition)

for

For loops repeat code a specific number of times. Perfect for processing every item in an array.

📍 Index (Position)

[i]

The index i tracks your position. Use array[i] to get the current item.

HAP surrounded by tangled code with an 'oops' expression

HAP's Confession:

  • I started my loop at 1 instead of 0 — I skipped the first item in my array!
  • I used <= instead of < with array.length — I got "undefined" for the last iteration because I went one too far.
  • I forgot to increment i — my loop ran forever and crashed the browser!
  • I tried to access skills[5] in a 5-item array — arrays are zero-indexed, so the last item is skills[4].

The Problem: Repetitive Code

Before I learned loops, I was calling my function once for each skill:

Without Loops — Repetitive Calls
// My robot has multiple skills to check
let skills = ["navigation", "calculation", "communication", "analysis", "learning"];

// Without loops, I call the function for EACH skill manually:
console.log("Checking: " + skills[0]);  // "navigation"
console.log("Checking: " + skills[1]);  // "calculation"
console.log("Checking: " + skills[2]);  // "communication"
console.log("Checking: " + skills[3]);  // "analysis"
console.log("Checking: " + skills[4]);  // "learning"

// What if I add 10 more skills? 100 more skills?
// I'd have to add a new line for each one!

Five skills means five lines of nearly identical code. This doesn't scale — and if I need to change the message, I have to change it in five places!

Arrays: Ordered Collections

Before we loop, let's understand arrays — they hold multiple values in order:

Array Basics
// Create an array with square brackets
let skills = ["navigation", "calculation", "communication"];

// Access items by index (position) — STARTS AT 0!
console.log(skills[0]);  // "navigation" (first item)
console.log(skills[1]);  // "calculation" (second item)
console.log(skills[2]);  // "communication" (third item)

// Get the number of items
console.log(skills.length);  // 3

// The last item is at index (length - 1)
console.log(skills[skills.length - 1]);  // "communication"

Zero-Indexed

The first item is at index 0, not 1. This trips up everyone at first!

Length Property

array.length tells you how many items. A 5-item array has indices 0-4.

Out of Bounds

Accessing an index that doesn't exist returns undefined, not an error.

Square Brackets

Use array[index] to get or set a value at a specific position.

Anatomy of a For Loop

A for loop has three parts inside the parentheses, separated by semicolons:

The Three Parts
//  keyword  init      condition    update
//    ↓        ↓           ↓           ↓
    for (let i = 0;  i < 5;       i++) {
        console.log("Iteration: " + i);
    }

// Output:
// "Iteration: 0"
// "Iteration: 1"
// "Iteration: 2"
// "Iteration: 3"
// "Iteration: 4"
HAP juggling web technologies

🟠 The Assembly Line:

Initialization: let i = 0 — Start at position 0
Condition: i < 5 — Keep going while this is true
Update: i++ — Move to the next position after each loop

How It Executes
for (let i = 0; i < 3; i++) {
    console.log(i);
}

// Step by step:
// 1. Initialize: i = 0
// 2. Check condition: 0 < 3? YES → run body, log 0
// 3. Update: i++ → i is now 1
// 4. Check condition: 1 < 3? YES → run body, log 1
// 5. Update: i++ → i is now 2
// 6. Check condition: 2 < 3? YES → run body, log 2
// 7. Update: i++ → i is now 3
// 8. Check condition: 3 < 3? NO → STOP

Looping Through Arrays

The real power comes when you combine loops with arrays:

Processing Every Item
let skills = ["navigation", "calculation", "communication", "analysis", "learning"];

// Loop through the array
for (let i = 0; i < skills.length; i++) {
    console.log("Checking skill: " + skills[i]);
}

// Output:
// "Checking skill: navigation"
// "Checking skill: calculation"
// "Checking skill: communication"
// "Checking skill: analysis"
// "Checking skill: learning"

// Add 100 more skills? The loop handles them automatically!

Using skills.length instead of a fixed number means the loop always processes every item, even if you add or remove skills later.

Building Results
let skills = ["navigation", "calculation", "communication"];
let activeCount = 0;

// Count how many skills are active
for (let i = 0; i < skills.length; i++) {
    if (skills[i].length > 10) {  // Skills with long names
        activeCount++;
        console.log("Long skill name: " + skills[i]);
    }
}

console.log("Found " + activeCount + " long skill names");
// "Long skill name: calculation"
// "Long skill name: communication"
// "Found 2 long skill names"

Loops are great for counting, filtering, or transforming data. Combine them with conditionals for powerful processing!

Common Loop Patterns

Here are patterns I use with my Robot ID Card:

Pattern 1: Process Each Item
let tasks = ["scan", "analyze", "report"];

for (let i = 0; i < tasks.length; i++) {
    console.log("Executing: " + tasks[i]);
}
Pattern 2: Build a Total
let scores = [85, 92, 78, 95, 88];
let total = 0;

for (let i = 0; i < scores.length; i++) {
    total = total + scores[i];
}

console.log("Total: " + total);  // 438
Pattern 3: Find a Match
let skills = ["navigation", "calculation", "communication"];
let found = false;

for (let i = 0; i < skills.length; i++) {
    if (skills[i] === "calculation") {
        found = true;
        console.log("Found at index " + i);
    }
}

if (!found) {
    console.log("Not found");
}
Pattern 4: Transform Each Item
let skills = ["nav", "calc", "comm"];
let formatted = [];

for (let i = 0; i < skills.length; i++) {
    formatted[i] = skills[i].toUpperCase();
}

console.log(formatted);  // ["NAV", "CALC", "COMM"]

Try the Skill Scanner Demo

I built an interactive tool where you can watch a for loop process an array step by step. See the loop counter increment, watch items get processed, and understand exactly how loops work!

🔬 Skill Scanner: Watch the loop iterate through HAP's skills array. See the index change, the current item highlight, and the output build up — all in slow motion!

→ Launch the Skill Scanner Demo

🎓 Loops Quick Reference

1

Arrays Start at Index 0

The first item is array[0], not array[1]. A 5-item array has indices 0, 1, 2, 3, 4.

2

Use < Not <= with Length

i < array.length stops at the last valid index. Using <= goes one too far!

3

Don't Forget i++

The update step i++ moves to the next item. Without it, your loop runs forever!

4

Use array.length for Flexibility

Don't hardcode the number of items. array.length adapts if you add or remove items.