← All lessons/Arrays· Lesson 23 of 32

Looping over an array

Use a for loop with array[i] and array.length to do something with every item — like drawing one shape per element.

About 8 min

One pass, every item

Arrays and for loops are a perfect match. Let the counter i walk from 0 up to array.length, and use array[i] to grab each item in turn:

let nums = [10, 20, 30];
for (let i = 0; i < nums.length; i++) {
  println(nums[i]);
}
Print every item.

Why < nums.length?

Indexes run from 0 to length - 1. Using i < nums.length (not <=) stops exactly after the last real item.

A shape per item

Here each number in the array becomes the diameter of a circle. The loop draws one ellipse for every item, all the way down the canvas:

Four circles, one per array item.

Your turn

An array sizes holds [20, 40, 60, 80, 100]five numbers. Loop over it with a for loop and draw one ellipse per item, using sizes[i] for both the width and the height. That's five ellipses in all.

Hints