Please enable JavaScript to use CodeHS

JavaScript Tutorial

Looping Through Arrays in JavaScript

An array is like a sushi conveyor belt: every plate has an index, and a for loop is the chef who inspects each one in order. Learn the classic index loop, why arr.length keeps it working, and the sneaky off-by-one bug.

javascript ~20 min Beginner friendly
The Big Idea

Why loop through an array?

Arrays are great for storing lots of data in a single variable. You already know how to grab one item with its index, like nums[3]. But what if you want to go through your entire list? Say we have an array of numbers, and we want to print every number that is even:

main.js
let nums = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34];

A number is even when dividing by 2 leaves no remainder, which we can check with the modulus operator: nums[0] % 2 == 0. Without a loop, we would have to write one if statement for every single index:

theHardWay.js
if (nums[0] % 2 == 0) {
    console.log(nums[0]);
}
if (nums[1] % 2 == 0) {
    console.log(nums[1]);
}
if (nums[2] % 2 == 0) {
    console.log(nums[2]);
}
// ...seven MORE of these?! No thanks.

Whew, that is a lot of typing, and the same if statement over and over. Wouldn't it be nice if we could just loop through the array and apply the same check to each item? Lucky for us, we can!

Picture a sushi conveyor belt: the plates are the array items, each sitting at its own index. Instead of you reaching for plate 0, then plate 1, then plate 2 by hand, a loop is the chef who slides every plate past the inspection window, one per lap, and runs the same code on each one.


The Chef's Routine

The classic index loop

One way to loop through an array is with a for loop. To know how many laps the loop should make, we need the length of the array. Every array keeps count of its own items in array.length:

main.js
let length = nums.length;
console.log(length);   // prints 10 because there are 10 items in nums
Console
10

Now we can write the most famous loop in programming. Memorize this shape, because you will type it thousands of times:

main.js
for (let i = 0; i < nums.length; i++) {
    // code to apply to each item in the array
}

Here is how the three parts of the header team up with the array:

  • let i = 0 starts i at 0, because the first index is 0, not 1.
  • i < nums.length keeps the loop going while i is a real index. With 10 items, the last index is 9, so we stop before i reaches 10.
  • i++ moves the belt: after each lap, i slides to the next plate.

Inside the body, nums[i] is the item currently in front of the chef. On lap 0 it is nums[0], on lap 1 it is nums[1], and so on. Back to our plan of printing the even numbers, which is way easier than writing 10 if statements:

evens.js
let nums = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34];

for (let i = 0; i < nums.length; i++) {
    let current = nums[i];      // gets the item at index i
    if (current % 2 == 0) {    // is it divisible by 2?
        console.log(nums[i] + " is even!");
    }
}
Console
0 is even!
2 is even!
8 is even!
34 is even!

Why nums.length and not 10? Because arrays change! If you push() three more numbers onto nums, the loop with i < nums.length automatically makes 13 laps and still visits every item. A loop hard-coded with i < 10 would silently skip the new ones. Let the array count itself.


Interactive

Try it: the conveyor loop machine

This belt is a real JavaScript array called belt. Press Run the loop and watch the chef work: each lap, the condition is checked, the plate at index i glides into the inspection window, the body logs it, and i++ advances the belt. When the condition turns false, the belt stops. Then push() a plate and run again: the loop adapts to the new length all by itself. Feeling brave? Flip on the <= bug and see what the chef finds on the extra lap...

Conveyor Loop Machine

live loop
for (let i = 0; i < belt.length; i++) { console.log(i + ": " + belt[i]); }
i = ?
BELT STOPPED
belt.length = 5 belt[i] = ? press Run to start the belt

// the belt holds 5 plates, at indexes 0 through 4

Console
// console output will appear here

Bug Patrol

The <= gotcha: a plate that does not exist

The number one array loop bug is using <= instead of < in the condition. It looks harmless, but think it through: an array with 3 items has length 3, and its indexes are 0, 1, and 2. There is no index 3. The condition i <= snacks.length lets i reach 3 anyway, so the loop takes one extra lap and asks for a plate that is not there:

offByOne.js
let snacks = ["tuna", "salmon", "egg"];

// BUG: should be i < snacks.length
for (let i = 0; i <= snacks.length; i++) {
    console.log(i + ": " + snacks[i]);
}
Console
0: tuna
1: salmon
2: egg
3: undefined

JavaScript does not crash when you read past the end of an array. It just hands back undefined and keeps going, which can quietly mess up the rest of your program. If you ever see a mysterious undefined at the end of your output, check your loop condition first!

Remember the pattern: with an array, the condition is almost always i < arr.length. The last real index is arr.length - 1, and < makes the loop stop exactly there. Try this bug live in the conveyor machine above and watch the chef inspect an empty slot.


Modern Shortcut

The for...of loop

A for...of loop is another great tool for looping over arrays. The cool thing about for...of is that it hands you each element directly, so you never touch an index at all:

main.js
for (let variable of array) {
    // code to apply to each element in the array
}

Each lap, the next element of the array is stored in the variable, so we can use number instead of nums[i]. (You can name that variable anything you want.) Here are both loop styles finding the even numbers, side by side. Run it and compare:

iteratingOverAnArray.js
let nums = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34];

console.log("Standard for Loop");
for (let i = 0; i < nums.length; i++) {
    let current = nums[i];
    if (current % 2 == 0) {
        console.log(nums[i] + " is even!");
    }
}

console.log("*************");
console.log("for...of Loop");
for (let number of nums) {
    if (number % 2 == 0) {
        console.log(number + " is even!");
    }
}
Console
Standard for Loop
0 is even!
2 is even!
8 is even!
34 is even!
*************
for...of Loop
0 is even!
2 is even!
8 is even!
34 is even!
  • Try adding a few more even and odd numbers to the nums array. What happens?
  • Add an else statement to print out when the number is odd.
  • In the for...of loop, try renaming the variable number to num. What happens?
  • Which type of loop do you prefer?

Which loop when? for...of is great when you just need each value, and there is no index to get wrong, so no off-by-one bugs! Use the index loop when you actually need i, like printing positions, changing items with nums[i] = ..., or looping over two arrays at once.


More Power

Doing math with loops

If we have an array of numbers, iterating makes it easy to compute things like the sum, average, minimum, and maximum. Say we have an array storing the temperatures of a perfect spring week:

main.js
let temps = [69, 70, 64, 60, 68, 70, 75];

To find the average (sum divided by the number of items), create a variable to store the sum before the loop. Then loop over the array, adding each temperature onto the sum. Finally, divide by temps.length:

Finding the minimum works the same way: start a min variable at the first temperature, then check each item. If it is smaller than the current min, update min. Note that the second loop below uses for...of, just to show that either type of loop works. Can you add code to find the maximum temperature?

temperatures.js
let temps = [69, 70, 64, 60, 68, 70, 75];

// Finds the average temperature
let sum = 0;
for (let i = 0; i < temps.length; i++) {
    sum += temps[i];          // adds each temperature to the sum
}
let average = sum / temps.length;
console.log("Average temperature: " + average);

// Finds the lowest temperature
let min = temps[0];
for (let temp of temps) {
    if (temp < min) {
        min = temp;
    }
}
console.log("The lowest temperature this week was: " + min);
Console
Average temperature: 68
The lowest temperature this week was: 60

Why does sum live outside the loop? If it were created inside the body, it would reset to 0 on every lap and the total would never grow. Create your "collector" variables before the loop, update them inside it, and use them after it.


Your Turn

Practice: game scores

1

Average, highest, and lowest score

Create an array to store the following set of game scores: 200, 145, 90, 84, 106, 213, 300, 214. Then use loops to find and print:

  • the average game score,
  • the highest game score,
  • and the lowest game score.

Try using both the standard for loop and the for...of loop. Which do you like better?

gameScores.js
// Create an array to store the game scores
let scores = [200, 145, 90, 84, 106, 213, 300, 214];

// Find the average game score (standard for loop)
let sum = 0;
for (let i = 0; i < scores.length; i++) {
    sum += scores[i];
}
console.log("Average score: " + sum / scores.length);

// Find the highest and lowest scores (for...of loop)
let highest = scores[0];
let lowest = scores[0];
for (let score of scores) {
    if (score > highest) {
        highest = score;
    }
    if (score < lowest) {
        lowest = score;
    }
}
console.log("Highest score: " + highest);
console.log("Lowest score: " + lowest);
Console
Average score: 169
Highest score: 300
Lowest score: 84

Notice that highest and lowest both start at scores[0], a real value from the array. Starting them at 0 would break the lowest-score search, because every score is bigger than 0!


Beyond Numbers

Looping with graphics

Arrays can store more than numbers and strings; they can hold graphics objects too. This program uses the CodeHS graphics library (commands like Rectangle and add() only work in the CodeHS graphics editor). First, a loop builds an array of squares. Then a timer calls blink every 100 milliseconds, which loops over the array and gives every square a random color. Without an array and a loop, we would have to recolor each square individually!

blinkingSquares.js
let WIDTH = 50;
let NUM_SQUARES = getWidth() / WIDTH;
let SPACE = 5;
let squares = [];   // creates an empty array to store the squares

// Creates an array of squares
for (let i = 0; i < NUM_SQUARES; i++) {
    let square = new Rectangle(WIDTH, WIDTH);
    square.setPosition(WIDTH * i + SPACE * i, getHeight() / 2);
    add(square);
    squares.push(square);
}

// Sets a timer to call the blink function every 100 milliseconds
setTimer(blink, 100);

function blink() {
    for (let i = 0; i < squares.length; i++) {
        squares[i].setColor(Randomizer.nextColor());
    }
}
Canvas (the colors change every 100 ms!)

Explore ideas to push it further:

  • Try changing the number of squares.
  • Try adding code to blink that moves each square to a random position. You can use Randomizer.nextInt(low, high) to get a random number between a low and high value.

Check Yourself

Quick quiz

Use this array to answer the questions:

quiz.js
let belt = ["tuna", "salmon", "egg", "shrimp"];

1. What does for (let i = 0; i < belt.length; i++) { console.log(belt[i]); } print?

2. You change the condition to i <= belt.length. What happens?

3. Why write i < belt.length instead of i < 4?

Keep learning JavaScript

You can now send a loop down any array: printing plates, summing scores, recoloring squares. Next, brush up on array basics or learn the built-in methods that search arrays for you.